Y. Georgiev
Y. Georgiev

Reputation: 610

Puppeteer [Error: Execution context was destroyed, most likely because of a navigation.]

I have a piece of code submitting a form. After that form I need a selector (await page.waitForSelector("selector")) to know if the submition has failed or not.

The code fills all the fields in the form and submits it successfully. The problem here is that when the form is submitted, I'm redirected to another page and the context is then lost, or at least that's my theory.

// fill information
await page.type("#email", email)
await page.type("#password", password)
await page.type("#confirm-password", password)

// submit form
await page.click("#register-submit-button")

// wait for selector
await page.waitForSelector(".page-login")

I've tried with await page.waitForNavigation(), instead of waiting for a selector, and got the same result.

I searched on the internet for a soution but nothing worked for me. I'd be grateful if anyone of you smart people can solve this!

Upvotes: 7

Views: 12096

Answers (1)

Vaviloff
Vaviloff

Reputation: 16838

The official docs say this about your situation:

Bear in mind that if click() triggers a navigation event and there's a separate page.waitForNavigation() promise to be resolved, you may end up with a race condition that yields unexpected results. The correct pattern for click and wait for navigation is the following:

// submit form amd wait for navigation to a new page
await Promise.all([
  page.click("#register-submit-button"),
  page.waitForNavigation(),
]);

// then do whataever is necessary on that new page
await page.waitForSelector(".page-login")

Upvotes: 13

Related Questions