Reputation: 13
I'm trying to create a bookmarklet to open links with specific text, but I'm facing a problem with the setTimeout
portion ...
javascript:(function(){
function clickLink(link) {
if (document.createEvent) {
var event=document.createEvent("MouseEvents");
event.initMouseEvent("click", true, true, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
link.dispatchEvent(event);
} else if (link.fireEvent) {
link.fireEvent("onclick");
}
}
l=document.links;
for(var i=0;i<l.length;++i) {
var lL=l[i].innerHTML.toLowerCase();
if(lL.indexOf("click here")!=-1 || lL.indexOf("how")!=-1)
setTimeout(function() {clickLink(l[i]) }, 1000);
}
};
})();
If I try setTimeout(clickLink(l[i]), 1000);
, then it works, but it runs immediately rather than waiting for the timeout!
Also want to know one more thing that clicking links this way will fire mousedown/mouseup event? If not then how can I programmatically click links which will also fire mousedown/mouseup events?
Upvotes: 1
Views: 238
Reputation:
You're coming across the usual "loop variable in a lambda" problem: by the time the timeout is done, i
will be past the end of document.links
and l[i]
will be undefined
. You could just wrap that part in a(nother) function:
(function(item) {
setTimeout(function() { clickLink(item); }, 1000);
})(l[i]);
Upvotes: 1