I used AJAX to get data that I named variable myPubscore. Now I\'m trying to send myPubscore to another js file. myPubscore prints fine in Ajax, but when I print just before sen
When using an asynchronous call like $.ajax
or fetch
or XMLHttpRequest
, its callback runs at a [much] later point in the future when the surrounding scope already ran so you need to use the results of the call inside the callback as explained in How do I return the response from an asynchronous call?
In Chrome, the onMessage API event won't recognize a Promise returned by the listener so to be able to use sendResponse asynchronously you need to return true
from the onMessage listener and call sendResponse in the ajax callback:
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;
}
});
async
keyword noteNote that you can't mark the onMessage listener with the async
keyword when returning true
because it would actually return a Promise
object to the API, which is not supported in Chrome extensions API. In this case use a separate async function or an async IIFE, example.
P.S. If you use WebExtension polyfill you can return a Promise from the onMessage listener and use async
function as a listener directly. In Firefox this is how the API works out-of-the-box.