多个标签Chrome扩展程序问题

时间:2013-05-13 22:30:37

标签: google-chrome-extension content-script

如果网址/ 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); })
  };
}

2 个答案:

答案 0 :(得分:1)

您可以执行类似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);
    }
  });
});

答案 1 :(得分:0)

由于window === top,您正面临这个问题。因此,您的title变量从上次打开的标签中获取其值。因此,如果在A之后打开B,则title从B获取其值。尝试:检测调用脚本的标签ID,获取那个标签的网址,然后成为您的{{ 1}}变量。如下:

title