The website is: lexin.nada.kth.se/lexin/#searchinfo=both,swe_gre,hej;
My script is:
function main(){
var links=document.getElementsByTagName("a");
alert("There are " + links.length + "links.");
}
main();
Running the script gives me two alert messages saying
There are 0 links.
Any ideas why I can't get the right amount of links from the document? And why do I get the alert twice?
The alert fires more than once because that page contains iFrames (with, de facto, the same URL as the main page). Greasemonkey treats iFrames as if they were standalone web pages. Use @noframes
to stop that.
The script is not finding the links because they are added, by javascript, long after the page loads and the GM script fires. This is a common problem with scripts and AJAX. A simple, robust solution is use waitForKeyElements()
(and jQuery).
Here is a complete sample script that avoids the iFrames and shows how to get dynamic links:
// ==UserScript==
// @name _Find elements added by AJAX
// @include http://YOUR_SERVER.COM/YOUR_PATH/*
// @match http://stackoverflow.com/questions/*
// @require http://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js
// @require https://gist.github.com/raw/2625891/waitForKeyElements.js
// @noframes
// @grant GM_addStyle
// ==/UserScript==
/*- The @grant directive is needed to work around a design change
introduced in GM 1.0. It restores the sandbox.
*/
var totalUsrLinks = 0;
waitForKeyElements ("a[href*='/users/']", listLinks);
function listLinks (jNode) {
var usrMtch = jNode.attr ("href").match (/^.*\/users\/(\d+)\/.*$/);
if (usrMtch && usrMtch.length > 1) {
totalUsrLinks++;
var usrId = usrMtch[1];
console.log ("Found link for user: ", usrId, "Total links = ", totalUsrLinks);
}
}
It's returning an HTMLcollection because of .getElementsByTagName
and because of that, you will have to state the HTMLcollection with .getElementsByTagName
and then find the length, and alert it. It will look like this...
(function main(){
var links = document.getElementsByTagName("a").length
alert("There are "+ links + " links.");
})()
I added an IIFE or an Immediately-Invoked-Function-Expression more on IIFEs here, so you don't have to call the function, and so the code is small and able to be "swallowed". lastly, it's alerting 2 alert boxes, because there's one[alert box] in the function and you're calling that function so it's going to do the same thing.