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.