Chrome存储给出未定义的存储计时器

Chrome storage giving undefined for stored timer

本文关键字:存储 计时器 未定义 Chrome      更新时间:2023-09-26

我正在制作一个chrome扩展,我正在使用chrome存储来存储变量。实际上,我首先从用户输入一个计时器,然后在每T秒后刷新页面,这些都是用户输入的。因此,为了存储这个时间,我使用了chrome存储,像这样:

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.
}
});

谁能帮助为什么currentTimer仍然未定义。我调试了很长时间,但没有找到解决方案。

问题是,一旦页面刷新currentTimer将得到NULL值,因为它是由用户只输入一次。

当原始函数已经完成时,所有chrome.* API回调都是异步调用的,这也意味着chrome.* API调用后的下一个语句在回调之前执行

  1. 将需要结果的代码放入回调中:

    chrome.storage.sync.get('something', function(item) {
           setTimeout(someFunction, item.value);
    });
    
  2. 如果在内容脚本中需要结果,则在新消息中返回值:

      内容脚本:
    • chrome.runtime.sendMessage({request: "doSomething"});
      chrome.runtime.onMessage.addListener(function(msg) {
          if (msg.response) {
              // do something with the received msg.response
          }
      });
      
    • 背景脚本:
    • 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); }
      }