Search code examples
javascriptgreasemonkey

Page reload don't stop in Greasemonkey-Script. What's wrong?


I wrote a script in Greasemonkey to check if a button exists and then click it. Else to reload the page.

Problem: The Button is found and clicked correctly. The page should not reload anymore but keeps on reloading and reloading.

What could be wrong????

Here is the code of my script:

(function() {
    'use strict';

    var zeilen = document.getElementsByClassName('content-card-entry fcb-row fcb-clear');
    for (var i = 0; i < zeilen.length; i++) {
        var zeile = zeilen[i];
        // Zeile mit Block 
        if (zeile.children[0].children[0].innerHTML == "247")

        {

            //Den String der ID auslesen
            var IDString = zeile.children[0].children[0].id;
            //Den Identifikationsstring ctlxxx auslesen
            var ClickID = IDString.substr(42, 5);

            //Den ClickString zusammenbauen
            var anfang = "ctl00_ContentMiddle_TicketList1_GridView1_";
            var ende = "_LinkButton1";
            var clickstring = anfang+ClickID+ende;

            //Den Button suchen
            var element = document.getElementById(clickstring);


            //Wenn der Button vorhanden ist klicken und mir eine Nachricht senden
          
            
            element.click();
            
}
else
	{
		location.reload();
	}
	}	
    
	
})();


Solution

  • You loop over a set of elements, and do "click or reload the page" for each of them. That means unless every single one of those elements is the button you're looking for, you're gonna reload the page.

    Put a return after element.click(), so that your entire function exits if the button is found, and put location.reload() after the for loop, so that it is only called if the for loop terminated without returning from the function.