0

I want to click through a gallery. Since I don't know how many pictures in the gallery are, I think I need a while loop. When I got to the last image, the next picture's button's classname changes to next-photo is-hidden until then it's simply next-photo. So my goal is to have a while loop and when this button becomes hidden, break out from the loop, until then it should be called repeatedly. Here I stand now:

async function openGallery(page) {
  await page.evaluate(async () => {
    const delay = ms => new Promise(resolve => setTimeout(resolve, ms));
    let randomTime = 250;
    let clickOnImage = document.querySelector('div.image');
    let nextbutton = document.querySelector('button[class="next-photo"]');
    let closeGallery = document.querySelector('button[class="close-gallery"]');
    let lastImage = document.querySelector('button[class="next-photo is-hidden"]');
    if (clickOnImage) {
      clickOnImage.click();
    }
    while (nextbutton) {
      nextbutton.click();
      if (lastImage) {
        closeGallery.click();
        break;
      }
      await delay(randomTime);
    }
  });
}

But now, when I reach the last picture, the program won't break out of loop, or in other words, other codes after this one won't execute. And the gallery won't close.

What am I missing?

2 Answers 2

2

Your main issue is probably that you're only searching for lastImage before all the clicking has been done, which means it doesn't exist yet. A fix would be to move that line to within the while loop, but in general the code you've given all looks a bit verbose. I'd probably use some kind of recursive function instead, similar to the below:

function updateContent() {
  setTimeout(function() {
      var button = document.getElementById('button');
      button.innerHTML = parseInt(button.innerHTML) + 1
      if (button.innerHTML === '5') {
          button.className = "unclickable"
          button.disabled = true
      } else {
          button.click()
      }
  }, 500)
}
<button id="button" class="clickable" onclick="updateContent()">1</button>

Sign up to request clarification or add additional context in comments.

Comments

1

You are setting lastImage once at the beginning before the is-hidden class is added. Once the is-hidden class is added later it doesn't matter because lastImage is already set.

You could do lastImage = document.querySelector('button[class="next-photo is-hidden"]'); again each time right before if (lastImage) {.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.