Introduction
I have a problem with my extension for Chrome. It should show a small overlay popup (created in jQuery) with Google search results based on your text selection. Basically, you should be able to select text on any page, right-click on it (context menu), click "Search by Selected Keyword", and a small window will appear on the same tab as the overlay with all Google search results.
Problem
It works as described, HOWEVER only for the first time. When I highlighted another keyword and its search, the extension is still REMEMBERS preceded by keywords and at the same time throws 2 windows. And if I were looking for another keyword that would give me 3 windows with two previous searches and a new one ...
I tried to remove the listener in the background of the script after it was executed, but it did not work. It looks like there are old listeners, and they are responsible for the request from the script content. Can I somehow remove them?
I tried to put:
chrome.extension.onConnect.removeListener(listener);
at the end of the getClickHandler () function, but does not work.
I also thought that perhaps this piece of code in the background of the script is doing this, but not sure if
return function(info, tab) {
Please have any suggestions?
Thank you very much in advance!
PS. , . , . , 2 , ... , .
:
{
"name": "Easy search Accelerator",
"version": "1.0",
"manifest_version": 2,
"description": "Easily search for anything...",
"icons": {
"16": "icon.png",
"48": "icon.png",
"128": "icon.png"
},
"background": {
"scripts": ["sample.js"]
},
"permissions": [
"contextMenus",
"tabs",
"http://*/*",
"https://*/*"
],
"manifest_version": 2
}
/ script (sample.js):
chrome.contextMenus.create({
"title": 'Search for "%s"',
"contexts":['selection'],
"onclick": getClickHandler()
});
function getClickHandler() {
return function(info, tab) {
var url = "https://www.google.co.uk/search?q=" + info.selectionText;
chrome.extension.onConnect.addListener(function listener(port) {
console.assert(port.name == "searchQuery");
port.onMessage.addListener(function(msg) {
if (msg.keywordRequest == "Yes")
port.postMessage({keyword: url});
});
});
chrome.tabs.executeScript(null, { file: "jquery-1.7.2.min.js" }, function() {
chrome.tabs.executeScript(null, { file: "frame.js" });
});
};
};
script (frame.js)
var port = chrome.extension.connect({name: "searchQuery"});
port.postMessage({keywordRequest: "Yes"});
port.onMessage.addListener(function listen(msg) {
var test = msg.keyword;
$("body").append("<div style=\"position: fixed;top: 20px;right: 20px;z-index: 9999;\"><iframe style=\"border:1px solid #868686;-webkit-box-shadow: 2px 2px 20px 1px rgba(0, 0, 0, 0.5);\" src=\""+ test +"\" width=328 HEIGHT=240></iframe></div>");
});