USSURATONCAHI
USSURATONCAHI

Reputation: 105

Chrome Extensions "chrome.storage.local" data updating trouble

I am working on one chrome extension and i need to use local storage to send data from options page to background scritps.

Options page script:

function addToStorage(key, val){
    let obj = {};
    obj[key] = val;

    chrome.storage.local.set( obj, function() {
      if(chrome.runtime.lastError) {
        console.error(
          "Error setting " + key + " to " + JSON.stringify(val) +
          ": " + chrome.runtime.lastError.message
        );
      }
    });
}

Background:

chrome.storage.local.get('code', function(code) {
    ... with code.code ...
});

For example: Now chrome.storage.local code value is abcd
I'm performing addToStorage('code', '1234') from options page script
After that in background script value code only will change when i manually click "update" at chrome extesions page

How can i automatically get actual data at background script?

Upvotes: 0

Views: 873

Answers (1)

Rusty
Rusty

Reputation: 37

the background script will check only once when started as is.

You could pass a mesage from the options script to background scripts after you update the local storage and use that as a trigger to check storage.

try this:

Options page

function addToStorage(key, val){
    let obj = {};
    obj[key] = val;

    chrome.storage.local.set( obj, function() {
      if(chrome.runtime.lastError) {
        console.error(
          "Error setting " + key + " to " + JSON.stringify(val) +
          ": " + chrome.runtime.lastError.message
        );
      }
      chrome.runtime.sendMessage({status: "Storage Updated"}, function (responce) {
          console.log(responce);
      })
    });
}

Background Page:

chrome.runtime.onMessage.addListener(
    function (request, sender, responce) {
        if (request.status === "Storage Updated") {
            chrome.storage.local.get('code', function(code) {
                // ... with code.code ...
            });

            sendResponce({status: "Update Recieved"});
        }
    }
);

Hope that helps, message passing docs here: https://developer.chrome.com/extensions/messaging

Upvotes: 1

Related Questions