I\'m trying to write google chrome extension that accepts user-selected word and user-defined web site and searches this word on that site (via Google and contextmenu).There
var ar = JSON.parse(localStorage.getItem("arr")); // you should also use JSON.stringify to store the array
var menuitems = []; // array to hold menu item ID's and sites
for (i in ar)
{
menuitem = chrome.contextMenus.create({
"title": "find ' %s' в " + ar[i],
"contexts": ["selection"],
"onclick": function(e)
{
var baseUrl = "http://www.google.com/search?q=site%3A";
if (e.selectionText)
{
baseUrl += encodeURIComponent(menuitems[e.menuItemId]) + "&q=" + encodeURIComponent(e.selectionText);
chrome.tabs.create({ "url": baseUrl });
}
}
});
menuitems[menuitem] = ar[i]; // store the ID of the current menuitem with the site
}
Tested, this should do the trick. Notice I also added a few improvements, like using for (.. in ..)
for the loop, and encodeURIComponent
for the URL arguments (encodeURI
is for complete URLs, encodeURIComponent
is for URI components, i.e. arguments). Additionally, use JSON for storing data in localStorage
.
What I think you were doing wrong is that you defined clickHandler
after creating the menu item. When you create the menu item, clickHandler
is null, and nothing happens when you click it. I fixed this by simply defining the function inline in the menu item creation.
When you assign a function to onclick
property it is not evaluated right away. By the time it is evaluated your loop is ended long time ago and ar[i]
doesn't contain what you expect.
It is a classic javascript problem which is solved with closures:
chrome.contextMenus.create({
"title": "find ' %s' в "+ ar[i],
"contexts": [ "selection"],
"onclick" : (function(element) {
return function(info, tab) {
var baseUrl = "http://www.google.com/search?q=site%3A";
if (info.selectionText) {
baseUrl += element + "&q="+ encodeURI(info.selectionText);
chrome.tabs.create({"url": baseUrl});
}
}
})(ar[i])
});
We created anonymous function which is evaluated right away and returns a real event handler. The trick is that current ar[i]
value will now be always available as element
variable inside the closure.