2015-09-20 31 views
0

我正在做一个扩展名,我使用铬存储来存储一个变量。实际上,我首先从用户输入一个定时器,然后在每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值,因为它只能被用户输入一次。

+0

@wOxxOm我通过他们走了,但没有为我工作:( – GitCoder

+0

@wOxxOm能否请您详细的解决方案为,那么你的你是什么意思?不能立即返回值。您应该从sync.get回调中将新邮件发回给您的内容脚本。 ? – GitCoder

+0

看看[那个问题](http://stackoverflow.com/q/14220321/3959875)。似乎最好的重复候选人,并提供了一些关于这个问题的很好的解释。 – wOxxOm

回答

1

所有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); } 
      }