I created the following Greasemonkey script to be executed on Firefox for all websites. Here’s the script. The script basically gets all the links on the page and alerts the number of links. This is a small part of a project I am working on.
window.addEventListener("load", function(e) {
var links = window.document.getElementsByTagName("a");
//window.setTimeout(function(){alert(links.length);},3000);
alert(links.length);
}, false);
The script executed fine for some websites, but when I accessed reddit, the script is returning only 2 links, instead of all the links that are present on the page. When I tried to search for divs present on the page, it also returned only 2.
When I researched the page source, there was something related to inline javascript. But I could not understand it perfectly. Can anyone please help me why this is not working?
Thanks,
Sid
It has to be AJAX content loads. If you execute your code from the debugger it works fine. So the only explanation is that the content isn’t there after the
loadevent. Try wrapping it in a timeout (ugly, but this should prove my point).Now that you know what the problem is, you can follow the instructions in this SO question to create an AJAX event listener. Then you can recalculate your number of links whenever new content loads.
JavaScript detect an AJAX event