chrome扩展,将数据从内容传递到后台

时间:2013-06-21 02:20:54

标签: javascript json google-chrome-extension

我创建了一个由manifest.json,content.js和background.js组成的chrome扩展。在content.js中,我正在提取当前标签的URL,在background.js中,我正在打开一个新标签。我想做什么,哪个不起作用是从内容传递URL并将其附加到我在后台调用的URL。

content.js:

chrome.extension.onMessage.addListener(function(request, sender, sendResponse)
{
    if(request.greeting=="gimmieyodatas")
    {
    var output ="URL=";
    //check for the character '?' for any parameters in the URL
    var paramIndex = document.URL.indexOf("?");
    //if found, eliminate the parameters in the URL
    if (paramIndex > -1)
    {
        output += document.URL.substring(0, paramIndex);
    };
        sendResponse({data: output});
    }
    else{
        sendResponse({}); 
    }
});

background.js:

var output2;
chrome.tabs.getSelected(null, function(tab) {
  chrome.tabs.sendMessage(tab.id, {greeting:"gimmieyodatas"}, function(response) {
    output2 = response.data;
  });
});
chrome.browserAction.onClicked.addListener(function() {
    chrome.tabs.create({url: "http://www.google.com?" + output2}, function(tab) {
        chrome.tabs.executeScript(tab.id, {file: "content.js"}, function() {
            sendMessage();
        });
    });
});

当我从一个打开的标签页运行扩展程序时,它会在新标签页上打开Goog​​le,但它不会在Google网址中附加当前标签页的网址,这意味着“输出”数据不会传递给后台.js 。我做错了什么?

1 个答案:

答案 0 :(得分:1)

问题是,当打开新选项卡时,您没有告诉后台页面发送消息。对chrome.tabs.getSelected的调用仅在首次运行扩展时发生一次 - 每次打开新选项卡时都不会发生这种情况。

通过使用背景页面作为两个内容页面之间的中介,您走在正确的轨道上,但我建议采用不同的方法:

每次打开新标签时,都会通过清单文件加载内容脚本:

"content_scripts": [
    {
        "matches" : [
            "<all_urls>"
        ],
        "js" : [
            "content.js"
        ]
    }
],

使用更简单的内容脚本,只需在加载后立即向当前网页发送消息:

(content.js)

var paramIndex = document.URL.indexOf('?');
if (paramIndex > -1) {
    chrome.runtime.sendMessage({output2: 'URL=' + document.URL.substring(0, paramIndex)});
}

当后台页面收到消息时,它会将URL保存到全局变量:

(background.js)

var output2;
chrome.extension.onMessage.addListener(function(request, sender, sendResponse) {
    output2 = request.output2;
});

然后,您可以在单击操作按钮时加载该URL:

(background.js)

chrome.browserAction.onClicked.addListener(function() {
    chrome.tabs.create({url: "http://www.google.com?" + output2});
});