Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Puppeteer How to check if the page has redirected

I am trying to check with waitForNavigation() to see if the page switches or not. Here is the code I am using

if ((await page.waitForNavigation()) == null) {
  console.log("False");
  await browser.close();
} else {
  console.log("True");
  await browser.close();
}

For example, let us just say a box on the screen is there and you get redirected to another page. I want True or False to pop up on the console.log.

I had to switch up the answer a bit but here it is

if (newUrl == startingURL) {
  console.log("False");
  await browser.close();
} else {
  console.log("True");
  await browser.close();
}
like image 446
Neik0 Avatar asked Sep 06 '25 05:09

Neik0


1 Answers

If you only care about redirects, like HTTP redirects & window.location.href redirects, you can check the URL that you end up on and compare it to the URL you started with:

const startURL = 'https://example.com/redirect-start'
await page.goto(startURL)
if (page.url() === startURL) { console.log('False') }
else { console.log('True') }
like image 109
geekonaut Avatar answered Sep 07 '25 20:09

geekonaut