content script - Multiple Tab Chrome Extension Issue -
i've created basic extension searches google if url/html content fulfill requirements. works part, fails miserably when there multiple instances of extension. example, if load tab , tab b, click on page action tab a, directed search of tab b's content.
i don't know how silo script each tab, clicking tab a's page action result in search tab stuff. how can done? i'd appreciate suggestions!
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); }) }; }
you store title
associated tabid
, way when click on pageaction
uses correct title. changes these:
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 going remove array because otherwise // array grow without bounds, better remove // when tab closed can use pageaction more // once. a.splice(i,1); } }); });
Comments
Post a Comment