Tips for managing the variable within an asynchronous callback function

I am currently working on a Chrome extension and my goal is to display the selected text on the tab within a textarea located inside the plugin.

Although I have successfully implemented the function to retrieve the selected text, I am facing challenges in setting the value of the textarea element within the plugin.

Inquiry: What is the proper method for storing the value so that it can be passed to the textarea using data-binding?

HTML:

<div>
    <p>The selected text will be displayed here :</p>
    <textarea name="selectedText" id="selectedText" [(ngModel)]="selectedText"></textarea>
    <button (click)="getSelectedText()">Get the selected text</button>
</div>

TS:

export class CaptureComponent {
    selectedText = '';

    getSelectedText() {
        chrome.tabs.executeScript( {
            code: 'window.getSelection().toString();'
        }, function(selection) {
            this.selectedText = selection[0];
        });
    }
}

The selection[0] is functioning properly, indicating that the issue lies in how I am attempting to store the data. However, I am struggling to identify the necessary modifications.

Answer №1

The reference to `this` in your current method does not pertain to the component itself.

To rectify this issue, modify your callback function to utilize an arrow function for scope preservation:

fetchSelectedText() {
   chrome.tabs.executeScript( {
     code: 'window.getSelection().toString();'
     }, (selected) => {
       this.capturedText = selected[0];
    });
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best way to retrieve the outcomes of .query within a class?

Currently, I am working on a NodeJS application using coffee script. My objective is to save the results of a sql query executed by a class into a variable that can be returned by that same class. This is what I have so far: class dataBase mySQL = requ ...

Top method for achieving a smooth transition in a loading CSS3 animation

Having trouble implementing a fade in/fade out effect on a div with a CSS3 based login animation when a function is loaded. I have set up a jsfiddle but still can't get it to work. Any assistance would be greatly appreciated! http://jsfiddle.net/adam ...

Using jQuery .sortable() to reorder list items and update their IDs based on their new positions

My apologies for my limited English skills, but here is what I am trying to achieve. I have a list structured like this: <ul id="sortable" class="sortable"> <li id="1">1</li> <li id="2">2</li> <li id="3">3</li> &l ...

Tips for identifying truncated text when resizing the td element

While using the resize option in my table, I noticed that it cuts off some text. How can I determine the size at which the text begins to get cut off? https://i.sstatic.net/X7tKK.png This issue occurs when I resize the header https://i.sstatic.net/peycT. ...

Issues arise with the onscroll functionality when it is responsible for executing numerous conditional statements

My JavaScript function triggers various conditional statements based on the user's scrolling behavior. (Specifically, it adjusts the design of my navigation links as the window moves into different sections or rows.) // list of variables var pLink ...

Retrieve JSON web token from HTTP header following backend SAML2 authentication

I am facing a challenge in my Angular application where I need to read the JWT from the HTTP header after being redirected from the backend. Here is an overview of my authentication process: Once the user logs in successfully on the web browser, a POST r ...

Only the homepage experiences issues with the Bootstrap 4 mobile navigation menu failing to remain open

http://example.com/index.html I am in the process of building my first website using Bootstrap 4 beta. I have encountered an issue with the mobile navigation menu specifically on the HOME PAGE. When clicking the hamburger icon, the nav menu opens briefly ...

Unlocking the potential: transferring a variable from HTML to PHP, then showcasing it using JS - Chart.js

I am in need of displaying a chart on my website that is generated from SQL data. After some research, I have decided to utilize chart.js and found an example online. However, I have encountered a hurdle: My question pertains to passing a variable within ...

AngularJS does not allow empty spaces in textarea inputs

I am working on a form that includes a textarea element for users to input descriptions, however it does not allow any empty spaces. Users can only input alphanumeric and numeric characters, but no spaces. <textarea class="form-control" rows="4" maxl ...

Exploring the concept of defining multiple global files for each environment in Nightwatchjs adds

I'm facing a challenge with NightwatchJS as I attempt to configure multiple globals files based on different environments. While the documentation at suggests that this can be achieved, I'm having trouble implementing it correctly. It seems tha ...

Tips for changing the color of an icon when clicking a button

How can I dynamically change the color of an icon when clicked? Would using ngClass be the most efficient approach for this task? Currently, I have assigned a class to my icon. <ion-card> <ion-row> <ion-col> < ...

Combining nested Observables within an outer array without using inner subscribe (RxJS)

Looking at the TypeScript functions below, which are used for async HTTP-Calls: public retrieveAllMembersIdsFromGroup(groupId: string): Observable<string[]> public retrieveMember(memberId: string): Observable<Member> How can these be combined ...

Combining objects using ID with jQuery

Is there a simple way to merge two JavaScript objects like the example below? let arr1 = [ {"0": { id: "abdc4051", date: "2017-01-24" }}, {"1": { id: "abdc4052", date: "2017 ...

Asserting types for promises with more than one possible return value

Struggling with type assertions when dealing with multiple promise return types? Check out this simplified code snippet: interface SimpleResponseType { key1: string }; interface SimpleResponseType2 { property1: string property2: number }; inter ...

What is the process for importing a component at a later time?

I am attempting to import components with a delay in a seamless manner. My goal is to import the components discreetly so that they load smoothly in the background while viewing the homepage. I experimented with lazy loading, but found that it caused dela ...

React.js button classes in action

I am facing an issue with the active button and couldn't find a solution on stackoverflow. In my store, there are buttons for selecting product characteristics. Currently, I have managed to save one value in the state, but if the attribute category i ...

Docker: CORS policy is blocking access to XMLHttpRequest

After creating an ASP.NET Web Application (.NET Framework) project in Visual Studio 2022 and adding a web service to it, everything seemed to work fine when testing the web service call on Local IIS. However, things took a different turn when I tried runni ...

Generic abstract class encounters failure with Typescript TypeORM findOneBy({id: id}) operation

I have incorporated the "typeorm": "^0.3.7" module. import { IRepository, EntityBase } from "core" import { Database } from "../../db" import { EntityTarget, Repository } from "typeorm" export abstract clas ...

Can't get the font style to change on my website using the Chrome settings, what should I do?

When I adjust the default font display settings in Chrome (Settings > Appearance > Customize fonts) to something other than the default, the font on my webpage remains unchanged. An example of how it should appear Default/Changed (Times New Roman/Ca ...

A guide on creating tagged strings by parsing JSON data

I am currently working with next.js. In my json file, there is a string: { "title":"Just a text with <b>accent</b> inside", } I am trying to retrieve this string and return a modified version with the <b> tag includ ...