多标签Chrome扩展问题



我已经创建了一个基本的扩展,如果URL/HTML内容满足某些要求,搜索谷歌。它在大多数情况下是有效的,但是当有多个扩展实例时就会失败。例如,如果我加载选项卡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); })
  };
}

您可以将title与其关联的tabId存储在一起,这样当您单击pageAction时,它就会使用正确的标题。修改的内容如下:

background.js

title= [];
[...]
chrome.runtime.onMessage.addListener(function(request,sender,sendResponse){
  if (request.title != "") {
    title.push({tabId:sender.tab.id, title:request.title});
    sendResponse({confirm: "WE GOT IT."});
  }
});
[...]
chrome.pageAction.onClicked.addListener(function(tab) {
  title.forEach(function(v,i,a){
    if(v.tabId == tab.id){
      chrome.tabs.create({url: luckySearchURL + v.title});
      // Here I am going to remove it from the array because otherwise the 
      // array would grow without bounds, but it would be better to remove
      // it when the tab is closed so that you can use the pageAction more
      // than once.
      a.splice(i,1);
    }
  });
});

您正面临这个问题,因为window === top。因此,您的title变量从最后打开的选项卡获取其值。因此,如果B在A之后打开,title从B中获得其值。试试这个:检测调用脚本的标签Id,获取的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});
    });
});

最新更新