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
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.