Google chrome extension 多标签Chrome扩展问题

Google chrome extension 多标签Chrome扩展问题,google-chrome-extension,content-script,Google Chrome Extension,Content Script,我已经创建了一个基本扩展,如果URL/HTML内容满足某些要求,它将搜索Google。它在大多数情况下都能工作,但当有多个扩展实例时,它会失败得很惨。例如,如果我先加载选项卡A,然后加载选项卡B,但单击选项卡A的页面操作,我将直接搜索选项卡B的内容 我不知道如何将脚本发送到每个选项卡,因此单击选项卡A的页面操作将始终导致搜索选项卡A的内容。如何做到这一点?谢谢你的建议 background.js title = ""; luckySearchURL = "http://www.google.co

我已经创建了一个基本扩展,如果URL/HTML内容满足某些要求,它将搜索Google。它在大多数情况下都能工作,但当有多个扩展实例时,它会失败得很惨。例如,如果我先加载选项卡A,然后加载选项卡B,但单击选项卡A的页面操作,我将直接搜索选项卡B的内容

我不知道如何将脚本发送到每个选项卡,因此单击选项卡A的页面操作将始终导致搜索选项卡A的内容。如何做到这一点?谢谢你的建议

background.js

title = "";
luckySearchURL = "http://www.google.com/search?btnI=I%27m+Feeling+Lucky&ie=UTF-8&oe=UTF-8&q=";

chrome.runtime.onMessage.addListener(
    function(request, sender, sendResponse) {
        if (request.title != "") {
            title = request.title;
            sendResponse({confirm: "WE GOT IT."});
        }
    });

chrome.tabs.onUpdated.addListener(function(tabId, change, tab) {
    if (change.status === "complete" && title !== "") {
        chrome.pageAction.show(tabId);
    }
});

chrome.pageAction.onClicked.addListener(function(tab) {
    chrome.tabs.create({url: luckySearchURL + title})
})
contentscript.js

function getSearchContent() {
    url = document.URL;
    if (url.indexOf("example.com/") > -1)
        return "example";
}

if (window === top) {
    content = getSearchContent();
    if (content !== null) {
        chrome.runtime.sendMessage({title: content}, function(response) {
        console.log(response.confirm); })
  };
}

您面临此问题是因为
window===top
。因此,您的
title
变量从上次打开的选项卡中获取其值。因此,如果在A之后打开B,
title
从B获取其值。尝试以下操作:检测调用脚本的选项卡Id,获取该选项卡的url,然后该url将成为
title
变量。详情如下:

chrome.pageAction.onClicked.addListener(function(tab) {
    chrome.tabs.query({active:true},function(tabs){
           //this function gets tabs details of the active tab, the tab that clicked the pageAction

           var urltab = tabs[0].url;
           //get the url of the tab that called this script - in your case, tab A or B.

           chrome.tabs.create({url: urltab + title});
    });
});

您可以执行类似于将
标题
与其关联的
选项卡
存储在一起的操作,这样,当您单击
页面操作
时,它会使用正确的标题。这些变化将是:

background.js

title=[];
[...]
chrome.runtime.onMessage.addListener(函数(请求、发送方、发送响应){
如果(request.title!=“”){
title.push({tabId:sender.tab.id,title:request.title});
sendResponse({确认:“我们找到了。”});
}
});
[...]
chrome.pageAction.onClicked.addListener(函数(选项卡){
标题.forEach(功能(v、i、a){
if(v.tabId==tab.id){
create({url:luckySearchURL+v.title});
//这里我将从数组中删除它,因为
//数组将无限增长,但最好删除
//当选项卡关闭时,它将显示,以便您可以更多地使用页面操作
//不止一次。
a、 拼接(i,1);
}
});
});