2015-09-20 34 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); } 
      }