Pass Array Variable From Background.js To Content.js
Solution 1:
sendResponse
is being called before fourmTabs
gets populated, so it's still a blank array when you send it. All of your code from if(!fourmTabs)
through the sendResponse
call should be moved inside the callback from tabs.query
.
Edit:
You need to add return true;
just before your final lines in the addListener
callback-- your final three lines then should look like:
returntrue;
}
});
This is not particularly well documented, and I'm not sure I'm explaining it well, but because tabs.query
is asynchronous and you need to run it before you can get your response, the port used for messaging is being closed before tabs.query
finishes, and therefore before sendResponse
is actually being called, so the content script thinks it's getting a non-response.
Sourced largely from this chromium-extensions thread with a similar but different scenario (waiting on an AJAX call to complete before calling sendResponse
)
Solution 2:
Have you tried storing the value and calling it using chromes storage methods? I'm not sure if this is the best method, but I'm sure this will open up cross communication. Here's an example:
var setArray = [1, 2, 3, 5, [1, 2, 3]];
chrome.storage.local.set({'storageObjectName': setArray}, function () {
/* optional callback */
});
And from your other script
chrome.storage.local.get('storageObjectName', function(data) {
console.log(data);
});
Example of combining the two:
var setArray = ['my new data']; /* setting array in script 1 */
chrome.storage.local.set({'storageObjectName': setArray}, function (){
chrome.storage.local.get('storageObjectName', function (data) {
otherScriptFunction(data); /* call your other function from script 2 */
});
});
Post a Comment for "Pass Array Variable From Background.js To Content.js"