2013-05-13 2 views
0

URL/HTML 콘텐츠가 특정 요구 사항을 충족하는지 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

당신은 관련 tabId 당신이 올바른 제목을 사용하는 pageAction 클릭 그렇게를 저장하는 title 같은 일을 할 수 있습니다. 변경 사항은 다음과 같다 :

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); 
    } 
    }); 
});