Source page and contents of Chrome Extension Script Sync

Suppose I have the following code on my Chrome extension base page.

var opts; chrome.storage.local.get(options, function(result) { opts = result[options]; }); chrome.runtime.onMessage.addListener(function(request, sender, response) { if (request.message === 'getOpts') response(opts); }); 

In my script content, I access opts when sending messages.

 chrome.runtime.sendMessage({'message': 'getOpts'}, function(response) { console.log(opts); }); 

Is there any guarantee that options will be determined before the contents of the script are run? For example, when the browser starts, the background page will be executed, and, presumably, the callback to chrome.storage.local.get will be added to the message queue of the background page. Is Chrome ready to end this queue before entering content scripts?

I could call chrome.storage.local.get from the contents of the script, but my question is more general, since I have additional processing of asynchronous messages on my background page. At the moment, my content script is checking the source page to make sure everything is ready (using the interval to check), but I'm not sure if such checks are needed.

+5
source share
2 answers

Do not rely on your variable defined even if it is in your tests. In general, due to the usual time, your var should be set by the time it receives the message, but make sure you check this against your onMessage background. I dealt with this by recalling whether in the global I had already initialized the extension and did it, if necessary, from onMessage. Xan's answer shows how to use "return true" in this case to process the message after init initialization is complete.

See an example of this on my chrome extension (search for bCalled )

There you can see that I have a sendResponse method that takes care to determine if a callback has been called, and if not, return true (it is assumed that the async operation is running and the callback is called later)

You can also experiment and test this by luring the delay in the background code that this var loads.

0
source

You can reply asynchronously to a message.

 chrome.runtime.onMessage.addListener(function(request, sender, response) { if (request.message === 'getOpts') { chrome.storage.local.get('options', function(result) { response(result[options]); }); return true; // Indicate that response() will be called asynchronously } }); 

In the case of chrome.storage this is really stupid, as the API was specifically designed to add a workaround for using localStorage + messages in content scripts; You can directly request content scripts.

But in the general case of asynchronous processing, you can delay the response to the message. You just need to return the true value from the listener to indicate that you are not finished yet.

+1
source

All Articles