I'm having trouble figuring out how to use Chrome extension code asynchronously. The docs say that
Most methods in the chrome.* APIs are asynchronous: they return immediately, without waiting for the operation to finish. If you need to know the outcome of that operation, then you pass a callback function into the method. That callback is executed later (potentially much later), sometime after the method returns.
The documentation on executeScript
seems to suggest that it is asynchronous, since it takes a callback that is called "after all the JavaScript has been executed".
Despite realizing all this, I'm having trouble figuring out how to use the script execution to my advantage.
Here's what I have in example.js
:
var firstWords = "data:text/csv";
document.addEventListener('DOMContentLoaded', function() {
chrome.tabs.query({ currentWindow: true }, function(tabs) {
tabs.forEach(function(tab) {
chrome.tabs.executeScript(tab.id, { file: "getFirstWord.js" }, function(result) {
console.log("result of executeScript: ", result);
firstWord = result[0];
firstWords += firstWord;
console.log("firstWords: ", firstWords)
});
console.log("AFTER EXECUTESCRIPT firstWords: ", firstWords)
});
console.log("AFTER FOREACH firstWords: ", firstWords)
});
console.log("AFTER QUERY firstWords: ", firstWords)
});
console.log("AFTER EVERYTHING firstWords: ", firstWords)
and in getFirstWord.js
:
console.log("hello from getFirstWord.js");
document.title.match(/\w*/)[0]
Somewhat unsurprisingly, the output is not what I wish:
AFTER EVERYTHING firstWords: data:text/csv
AFTER QUERY firstWords: data:text/csv
AFTER EXECUTESCRIPT firstWords: data:text/csv
AFTER EXECUTESCRIPT firstWords: data:text/csv
AFTER EXECUTESCRIPT firstWords: data:text/csv
AFTER FOREACH firstWords: data:text/csv
result of executeScript: ["Asynchronous"]
firstWords: data:text/csvAnsynchronous
result of executeScript: ["Washington"]
firstWords: data:text/csvAnsynchronousWashington
result of executeScript: ["Chicago"]
firstWords: data:text/csvAnsynchronousWashingtonChicago
The ultimate goal is to accumulate a string of all the desired data (and convert to CSV).
Is there some kind of .done
type of method, or some other way to use the call back, so that I can actually use the accumulated result once my query has finished?