Loops in GreaseMonkey
I'm developing my first greasemonkey script (trying to edit and add page content to a particular website) and for some reason, it refuses to work beyond one while
loop.. Eg :
var anchorTag = window.document.getElementsByTagName('a');
var anchorTagNumber = window.document.getElementsByTagName('a').length;
..
..
i = 0
j = 0;
function collectId(i,link) {
linkArray[j] = new Array(2);
linkArray[j][0] = i;
linkArray[j][1] = link;
j++;
}
while(i <= anchorTagNumber)
{
testHref = anchorTag[i].href;
testHTML = anchorTag[i]开发者_开发技巧.innerHTML;
patHref = /some regex/;
patCaptureId = /some regex/;
testId = patCaptureId.exec(testHref);
patHTML = /some regex/;
patHTML2 = /some regex/;
patHTML3 = /some regex/;
if(patHref.test(testHref) && !patHTML.test(testHTML) && !patHTML2.test(testHTML))
{
linkId = testId[1];
collectId(i,linkId);
}
i++;
}
Anything after this while loop ends, refuses to work. Even a simple alert
doesn't seem to execute. I have another while
loop with a similar structure, and if I put that one first, it executes and this one doesn't. Any Ideas ? Thanks in advance !
The most obvious problem is that the array is being overrun, which will cause the script to error-out.
This: while(i <= anchorTagNumber)
Should be: while(i < anchorTagNumber)
.
If an array has length 5, for example, its last element will have an index of 4.
Also, this:
var anchorTag = window.document.getElementsByTagName('a');
var anchorTagNumber = window.document.getElementsByTagName('a').length;
Can be simplified to:
var anchorTag = window.document.getElementsByTagName('a');
var anchorTagNumber = anchorTag.length;
That will speed the code slightly but also makes future code maintenance, or reuse, easier.
Instead of using a while, you could try a setInterval to call you function every 100 miliseconds.
interval = setInterval(function(){
iDidIt = doSomethin()
if(iDidIt){
clear interval;
}
},100)
精彩评论