2014-12-13 61 views
0

我希望將popup.js的值傳遞給background.js,以便我可以像期望的那樣打開網站。我使用localStorage變量作爲我的json的值。但是當發現我已經在參數輸入中找到了background.js的值時,函數openTab(輸入)始終是字符串「localStorage.input」本身。我該如何解決它?如何將popup.js的值傳遞給background.js

popup.js

window.onload=function() 
{ 
    localStorage.input=document.getElementById("search").value; 

    document.getElementById("submit").onclick=function() 
    { 
     chrome.extension.sendMessage({command:"start",input:localStorage.input}); 
    } 
} 

background.js

chrome.runtime.onMessage.addListener(
    function(request,sender,sendResponse) 
    { 
     switch(request.command) 
     { 
      case "start": 
       openTab(request.input); 
       break; 
     } 

     return true; 
    } 
); 

var openTab=function(input) 
{ 
    chrome.windows.create 
    (
     { 
      url:"http://www.baidu.com/s?wd="+input, 
     } 

    ); 
}; 
+0

你確定你想在窗口中的空白輸入,而忽略localStorage的值。加載()? – Todd 2014-12-13 09:51:51

+0

你正在混淆'extension.sendMessage'和'runtime.onMessage',你可能想避免這種情況。 (使用'runtime.sendMessage') – Xan 2014-12-13 13:49:00

+0

對不起,我改變了我的功能,並使用** runtime.sendMessage **,但它仍然不起作用 – Spikerman 2014-12-13 13:53:49

回答

0

嘗試了這一點

var lStore = localStorage.input || ''; 
window.onload=function() 
{ 
    var search = document.getElementById("search"); 
    search.value = lStore 

    document.getElementById("submit").onclick=function() 
    { 
     // var input = search.value; //try this as well 
     var input = lStore; 
     chrome.extension.sendMessage({command:"start",input:input}); 
    } 
} 
+0

對不起,我已經試過了。但它仍然無法工作。我發現在background.js中輸入**的值沒有任何意義。 – Spikerman 2014-12-13 13:27:02

+0

你也嘗試過'input = search.value' - 評論過的嗎? – Todd 2014-12-13 13:50:26

+0

謝謝!它運行成功!我發現問題是我的localStorage。我在popup.html中犯了錯誤:) – Spikerman 2014-12-16 11:00:08