Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Chrome Extension Background Page and Content Script Synchronization

Suppose I have the following code in my background page of a Chrome extension.

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 content script, I access opts with message passing.

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

Is there any guarantee that opts will be defined prior to a content script running? For example, when starting up the browser, the background page will run, and presumably the callback to chrome.storage.local.get will be added to the background page's message queue. Will Chrome finish processing that queue before injecting content scripts?

I could call chrome.storage.local.get from the content script, but my question is more generic, as I have additional async processing in my background page. At the moment, my content script checks with the background page to make sure everything is ready (using an interval to keep checking), but I am not sure whether such checks are necessary.

like image 777
dannyadam Avatar asked Nov 09 '22 16:11

dannyadam


1 Answers

You can actually answer 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 case of chrome.storage this is, indeed, stupid as the API was specifically designed to addess the roundabout nature of using localStorage + Messaging in content scripts; you can query from content scripts directly.

But in general case of async processing, you can postpone answering to the message. You just need to return a true value from the listener to indicate that you're not done yet.

like image 84
Xan Avatar answered Nov 15 '22 04:11

Xan