如何从popup.js向background.js提供价值

时间:2014-12-13 09:33:10

标签: javascript google-chrome-extension google-api

我希望将popup.js的值传递给background.js,以便我可以按照我的预期打开网站。我使用localStorage变量作为我的json值。但是当我发现函数 openTab(输入)的参数 input 中的background.js值已经是字符串" localStorage时.input" 本身。我该如何解决?

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,
        }

    );
};

1 个答案:

答案 0 :(得分: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});
    }
}