GitCoder
GitCoder

Reputation: 121

Chrome storage giving undefined for stored timer

I am making a chrome extension, and I am using chrome storage to store a variable. Actually I am first inputing a timer from user, and then refreshing the page after every T seconds those are given as input by user. So to store this time I used chrome storage like this :

chrome.extension.onMessage.addListener(function(request, sender, sendResponse) {
var currentTimer = request.timer;
if(currentTimer!=null){
    currentTimer = currentTimer*1000;
    alert(currentTimer);
    chrome.storage.sync.set({'x': currentTimer}, function() {
            console.log(currentTimer);
    });
}
if(currentTimer==null){
    chrome.storage.sync.get('x', function(items){
           currentTimer = items.value;
    });
    //Here currentTimer is undefined.
}
});

Can anyone help why currentTimer is still undefined. I am debugging for very long time, but could not arrive at a solution.

The problem is that as soon as page is refreshed currentTimer will get NULL value as it is been entered only once by user.

Upvotes: 0

Views: 142

Answers (1)

woxxom
woxxom

Reputation: 73556

All chrome.* API callbacks are invoked asynchronously when the originating function has already finished, which also means that the next statement after chrome.* API call is executed before the callback.

  1. Put the code that needs the result into the callback:

    chrome.storage.sync.get('something', function(item) {
           setTimeout(someFunction, item.value);
    });
    
  2. In case the result is needed in a content script, return the value in a new message:

    • content script:

      chrome.runtime.sendMessage({request: "doSomething"});
      
      chrome.runtime.onMessage.addListener(function(msg) {
          if (msg.response) {
              // do something with the received msg.response
          }
      });
      
    • background script:

      chrome.runtime.onMessage.addListener(function(msg, sender, sendResponse) {
          if (msg.request == "doSomething") {
              var tabId = sender.tab.id, frameId = sender.frameId;
              chrome.storage.sync.get('something', function(item) {
                  sendMessageToFrameId(tabId, frameId, {response: item.value});
              });
          }
      });
      
      function sendMessageToFrameId(tabId, frameId, msg) {
          // 1. frameId works since Chrome 41 and throws on prior versions
          // 2. without frameId Chrome 45 sends the message to wrong tabs
          try { chrome.tabs.sendMessage(tabId, msg, {frameId: frameId}); }
          catch(e) { chrome.tabs.sendMessage(tabId, msg); }
      }
      

Upvotes: 1

Related Questions