As usual, I have Googled this a fair bit and read up on the Message Passing API, but, again, I’ve had to resort to the good fellas at StackOverflow.
My question is this: When passing messages between a Google Chrome extension’s background page and content script, is there any way to make it asynchronous – that is, to delay the JavaScript until the messages are detected as being successfully being passed?
I have a function immediately after the message-passing function makes use of the localStorage data that is passed. On first runs the script always results in an error, due to the data not being passed fast enough.
Currently, I’m circumventing this with setTimeout(nextFunction, 250); but that’s hardly an elegant or practical solution, as the amount and size of the values passed is always going to change and I have no way of knowing how long it needs to pass the values. Plus, I would imagine, that passing times are relative to the browser version and the user’s system.
In short, I need it to be dynamic.
I have considered something like
function passMessages(){
chrome.extension.sendRequest({method: "methodName"}, function(response) {
localStorage["lsName"] = response.data;
});
checkPassedMessages();
}
function checkPassedMessages(){
if (!localStorage["lsName"]){
setTimeout(checkPassedMessages, 100); //Recheck until data exists
} else {
continueOn();
}
}
but I need to pass quite a lot of data (at least 20 values) and, frankly, it’s not practical to !localStorage["lsName1"] && !localStorage["lsName2"] etc etc. Plus I don’t even know if that would work or not.
Does anyone have any ideas?
Thanks
Update: Still no answer, unfortunately. Can anyone offer any help at all? :/
I don’t know whether I’m interpreting your question wrong. As far as I understand you are sending request from your extension page to a content script. The request handler in the content handler does some operation on the message passed after which you need the control back in the extension page. If this is what you need you have everything in the Google Extension Documentation. The following code works