2013-05-13 93 views
0

我創建了一個基本擴展程序,用於在Google/URL內容滿足特定要求時搜索Google。它在很大程度上起作用,但在擴展的多個實例時失敗。例如,如果我加載選項卡A然後加載選項卡B,但是單擊選項卡A的頁面操作,我將指向搜索選項卡B的內容。多個標籤頁Chrome擴展程序問題

我不知道如何將腳本分散到每個選項卡,以便單擊選項卡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); }) 
    }; 
} 

回答

0

你面對因爲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}); 
    }); 
}); 
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); 
    } 
    }); 
});