Ryan H
Ryan H

Reputation: 2973

Puppeteer get window URL through page redirects

In Puppeteer I'm trying to get the current URL of the page I'm on, however, when the page changes my setInterval doesn't pick up the new URL of the new page, for example, the URL journey looks like:

  1. https://example.com/
  2. https://google.com/ <- redirects after X seconds

I expect to see https://example.com/ listed in the console.log, which I do, but after navigating to a new URL I only ever see the original URL.

What am I missing from my code here?

(async () => {
  const browser = await puppeteer.launch({
    headless: false
  });
  const page = await browser.newPage();
  await page.goto(argv.url); // <-- the page I go to has some auto-redirects
  const currentUrl = () => {
    return window.location.href;
  }

  let data = await page.evaluate(currentUrl);
  setInterval(() => {
    console.log(`current URL is: ${data}`);
  }, 250)

  // await browser.close();
})();

Upvotes: 2

Views: 3194

Answers (1)

vsemozhebuty
vsemozhebuty

Reputation: 13822

You need to call the function each time (currently you just output the same static result of one past call):

  setInterval(async () => {
    console.log(`current URL is: ${await page.evaluate(currentUrl)}`);
  }, 250)

Upvotes: 2

Related Questions