简体   繁体   中英

console.log() not logging to console inside interval

I've looked through numerous post and can't seem to find the answer to my problem.

I have a console.log expression in my interval. When the code is ran in the console, it executes flawlessly, but refuses to console.log my string notifying the client sided user that the script is working.

Heres my code with notes:

  • initialize likes to 0
  • set interval and seconds (in ms)
  • define like button
  • define next picture button
  • if there's a likeButton, click likeButton
  • add 1 to likes and log to console the string
  • click the arrow to go to new photo
let likes = 0;

setInterval(() => {
    const likeButton = document.querySelector('svg[aria-label="Like"]');
    const nextButton = document.querySelector('svg[aria-label="Next"]');
    if (likeButton) {
        likeButton.parentNode.parentElement.click()
        likes++;
        console.log(`You've liked ${likes} post(s)`); 
    }
    nextButton.parentElement.parentNode.click();
}, 20000);

From the inspect source of a few posts I've looked at on Instagram, it looks like there are two states to the like button.

  • <svg aria-label="Like" /> when the post has not been liked yet.
  • <svg aria-label="Unlike" /> when the post has been liked by you already.

The problem is that const likeButton = document.querySelector('svg[aria-label="Like"]'); is returning the entire element as an object, and isn't a true/false value so if (likeButton) { will never be true but as @Unmitigated pointed out it can be "truthy." To determine if the button has been clicked and to eliminate any "truthy wiggle room" you need to look at the attribute on the likeButton element. You can use getAttribute() for this.

let likes = 0;

setInterval(() => {
    const likeButton = document.querySelector('svg[aria-label="Like"]');
    const nextButton = document.querySelector('svg[aria-label="Next"]');
    if (likeButton.getAttribute("aria-label") === "Like")) {
        likeButton.parentNode.parentElement.click();
        likes++;
        console.log(`You've liked ${likes} post(s)`); 
    }
    nextButton.parentElement.parentNode.click();
}, 20000);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM