What is the best way to save an AJAX success variable as a variable that is accessible outside of

After using AJAX to retrieve data as myPubscore, I encountered an issue when trying to pass myPubscore to another js file. While myPubscore printed correctly in Ajax, I faced a "ReferenceError" when attempting to print it just before sendResponse.

How can I successfully transfer myPubscore from AJAX to sendResponse? I came across a similar thread on SO discussing this problem, but the suggested solution was deprecated.

chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
    if (request.type == "articleUrl") {
        console.log("background heard articleUrl")
        console.log(request);
        var articleUrl = request;
        $.ajax({
        type: 'POST',
        url: `${url}/buttoncolor`,
        data: articleUrl,
        success: function urlFunction(data) {
        var myPubscore = data;
        console.log("myPubscore in ajax:")
        console.log(myPubscore);
        }
        })
    console.log("myPubscore in sendresponce:")
    console.log(myPubscore);
    sendResponse({score: "myPubscore"});
    }

updated background.js

chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
    if (request.type == "articleUrl") {
        console.log("background heard articleUrl")
        console.log(request);
        var articleUrl = request;
        $.ajax({
        type: 'POST',
        url: `${url}/buttoncolor`,
        success(data){
            console.log("incoming data");
            console.log(data);
            sendResponse(data);
            console.log("sent data");
            },
        });
        return true;
    }

content.js

        chrome.runtime.sendMessage({ "type": "articleUrl", "url": url }, function (response) {
            console.log("here's the response for sending the URL");
            console.log(response);
        });

Answer №1

When making an asynchronous call with a method like $.ajax, fetch, or XMLHttpRequest, the callback function will execute at a later time when the surrounding code has already run. This means that you must handle the results of the call inside the callback function itself.

Important tip for Chrome extension messaging

In Google Chrome, the onMessage API event does not recognize a Promise returned by the listener. To use sendResponse asynchronously, you should return true from the onMessage listener and then call sendResponse within the ajax callback like this:

chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
  if (request.type === 'articleUrl') {
    $.ajax({
      url: '...........',
      success(data) {
        sendResponse(data);
      },
    });
    return true;
  }
});

or

chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
  if (request.type === 'articleUrl') {
    fetch('https://www.example.org').then(r => r.text()).then(sendResponse);
    return true;
  }
});

Note about using the async keyword

It's important to note that you cannot use the async keyword in the onMessage listener when returning true. This is because it would return a Promise object to the API, which is not supported in Chrome extensions API. In such cases, you can use a separate async function or an async IIFE, like this example.

P.S. If you are using the WebExtension polyfill, you can return a Promise from the onMessage listener and directly use an async function as a listener. This is how the API works out-of-the-box in Firefox.

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

Tips for fading out two elements after completing a drag and drop action

Visit this Codepen for more examples - Codepen I have been developing a drag and drop feature in my application. Once the item is dropped, it transitions from red to green and fades out smoothly. The droppable element behind the draggable should also fad ...

What is the best way to display the ID value as a variable in a bootstrap modal dialog?

I originally thought figuring this out would be a breeze, but it's proving to be quite the challenge. After scouring for solutions without success, I find myself stuck. There's a list of dynamically generated buttons with unique id values that I ...

The JQuery datepicker fails to provide the date in the format mm/dd/yy

Recently, I attempted to transform a date into the dd/mm/yy format using JQuery datepicker. Unfortunately, my results displayed in the dd/mm/yyyy format instead. Here is the code snippet that I utilized: chkIn = $.datepicker.formatDate("dd/mm/yy", cinDate ...

What is the best way to position a semi-circular donut graph in the center?

I am attempting to showcase a doughnut or semi-circle chart within a materialize card, which is a responsive div element. My goal is to present simple data and utilize the chart as a progress bar. I took inspiration from the example provided in the HighCh ...

When transitioning between steps in Material UI React, the Vertical Stepper component should automatically scroll to the top of

When switching steps in Material UI's vertical stepper, it should automatically scroll to the beginning of the selected step. https://i.sstatic.net/fRX4E.png One potential solution is to utilize a ref to scroll to the stepper titles. More informatio ...

In JavaScript, implement event listeners exclusively on the main container and its immediate child elements

Is there a way to target just the main container and its second child elements for an event? Specifically, targeting id="container" and all elements with class="secondChild" Currently, I have a listener attached to all elements inside ...

Solution for dropdown boxes malfunctioning with required fields

Using Bootstrap 3 for field validation on forms has been effective, but there seems to be an issue with certain browsers such as ios safari not validating [required] form items. To address this, I created a script that checks if an element is marked as req ...

Retrieve the form of the chosen entity in Symfony2 using AJAX

Working on my mini project, I am faced with a task involving a list of customers, each accompanied by an "Update" button. When the user clicks on this button, I want to trigger an AJAX function that loads the form related to the customer clicked. Here is ...

Having difficulty interacting with a button using Selenium and JavaScript

For some reason, I am experiencing difficulty in clicking the login button even though my code appears to be accurate and there are no iframes or windows present: const { Builder, By, Key, until } = require('selenium-webdriver'); const { expect ...

Modifying the user interface (UI) through the storage of data in a class variable has proven to be

If I need to update my UI, I can directly pass the data like this: Using HTML Template <li *ngFor="let post of posts; let i = index;"> {{i+1}}) {{post.name}} <button (click)="editCategory(post)" class="btn btn-danger btn-sm">Edit</butto ...

embedding a button alongside the pager in an HTML document

I am encountering an issue with the positioning of a button in my paginated table setup. The button is currently displaying below the pager instead of being aligned on the left side of the page along with the pager. https://i.stack.imgur.com/gUiB9.png To ...

Error encountered while attempting to convert CSV file: InvalidStateError

I've implemented a JavaScript function to be triggered by the 'onclick' event of an HTML button: function exportReportData2() { if ($("#Report").val() != "") { var screenParametersList = buildScreenParameters(); var ...

Is there a way to match a string with information stored in a JSON file?

I have a snippet in my index.js that looks like this: if ('and' == trueWords) { console.log('Success!') } else { console.log('Failure!') } Below is the content of my json file: { "and": 1 } Appreciate your help! ...

Error encountered in ES6 destructuring syntax

Could you please assist me in figuring out what is causing the issue here: var foo = { bar: 1, baz: 2 }; var { bar, baz } = foo; I encountered an error SyntaxError: Unexpected token {. I am using node v5.4.1 and I am unsure if the problem lies wit ...

The error message "TypeError: Cannot access 'url' property of undefined in Strapi

I am facing an issue with a list of items where some have download links while others do not. Whenever I try to render an undefined URL, it triggers an error. To resolve this, I attempted the following: if (spectacle.pdf.url) { const pdf = spectacle.p ...

What is the best way to retrieve a variable within a nested function?

I'm struggling to access a variable from within a nested function in the following code: $(function() { var key = getRandomKey(dictionary); resetInputRow(dictionary[key]); $("#button").click( function() { var answer = key; ...

Update the table that includes a php script

I have a piece of PHP code embedded within a table tag that displays text from a database. I am looking for a way to automatically refresh this table every minute with updated content from the database, without refreshing the entire page. While I have co ...

Leveraging Azure's Machine Learning capabilities through a Javascript Ajax request

Has anyone successfully called the Azure Machine Learning webservice using JavaScript Ajax? Azure ML provides sample code for C#, Python, and R, but I'm struggling with JQuery Ajax. Despite my efforts, calling the webservice using JQuery Ajax result ...

Challenge with loading Ajax pages

I am facing an issue on my page where clicking a button loads a new page using ajax. However, if the button is clicked multiple times (three or more), the jQuery events start repeating. For example, if the new page contains a delete button with a script ...

CORS has restricted access to the XMLHttpRequest, despite the backend being configured correctly

I have a Flask backend integrated with React frontend. I encountered an issue while attempting to make a POST request to my backend. The error message states: Access to XMLHttpRequest at 'http://127.0.0.1:5000/predict' from origin 'http://lo ...