I have a chrome extension browser action that I want to have list a series of links, and open any selected link in the current tab. So far what I have is this, using jquery:
var url = urlForThisLink;
var li = $('<li/>');
var ahref = $('<a href="#">' + title + '</a>');
ahref.click(function(){
chrome.tabs.getSelected(null, function (tab) {
chrome.tabs.update(tab.id, {url: url});
});
});
li.append(ahref);
It partially works. It does navigate the current tab, but will only navigate to whichever link was last created in this manner. How can I do this for an iterated series of links?
@jmort253’s answer is actually a good illustration of what is probably your error. Despite being declared inside the
forloop,urlhas function scope since it is declared withvar. So your click handler closure is binding to a variable scoped outside theforloop, and every instance of the closure uses the same value, ie. the last one.Once Chrome supports the
letkeyword you will be able to use it instead ofvarand it will work fine sinceurlwill be scoped to the body of theforloop. In the meantime you’ll have to create a new scope by creating your closure in a function:Inside the
forloop say: