So I'm trying to write a script for tampermonkey for a site in which the image changes everytime you click on it. My goal is to click until I get the final image. The problem is that the script doesn't click anything and, if I try to print on console what is the object I'm trying to click it shows [object HTMLImageElement]. The code I'm using is:
var image;
document.addEventListener("DOMContentLoaded", function(){
sleep(1);
clicker();
});
function clicker()
{
var counter = 0;
console.log("current image: " + document.querySelector(".image"))
while(document.querySelector(".image").src != "https://site/image/4.gif" && counter < 10)
{
console.log("image at start: " + document.querySelector(".image"));
document.querySelector(".image").click();
counter ++;
console.log("click" + counter);
console.log("image at end: " + document.querySelector(".image"));
sleep(1);
}
};
/*function random(min,max)
{
return min + (max - min) * Math.random();
};*/
function sleep(s)
{
var now = new Date().getTime();
while(new Date().getTime() < now + (s*1000));
}
the image on the site is like:
<div>
<img data="" src="/image/2.gif" class="image">
</div>
the final output is: click1 image at end: [object HTMLImageElement]
image at start: [object HTMLImageElement] click2 image at end: [object HTMLImageElement]
[...]
I tried various things such as storing the queryselector in a variable or write down another function that returns me the image. The funny things is that if I run document.querySelector(".image").click(); on the console it works!
Edit
I finally solved by using a solution in the answers. Here the snippet:
var image;
var counter = 0;
var clickInterval;
function clickOnImage()
{
image = document.querySelector(".image");
if (image.src != "https://site/image/4.gif" && counter < 10) {
image.click();
counter++;
} else {
clearInterval(clickInterval);
}
}
window.addEventListener("DOMContentLoaded", function() {
clickInterval = setInterval(clickOnImage, 1000);
});