Puppeteer: "Execution context was destroyed, most likely because of a navigation"

In this article, I share how to fix the "execution context was destroyed, most likely because of a navigation" error that might happen while using Puppeteer.

Written by

Dmytro Krasun

Published on

Page, please, wait for navigation!

There might be a different context in which the error might be triggered, but the most often reason is that you try to execute code on the page after you reload the page.

To fix the “execution context was destroyed, most likely because of a navigation” error, use the page.waitForNavigation() function:

const navigationPromise = page.waitForNavigation({ waitUntil: ['load', 'networkidle2'] });
await page.click('<a link selector>');
// or page.addScriptTag({ content: 'window.location = 'https://example.com;' });
await navigationPromise;

The page.waitForNavigation() waits for the page to navigate to a new URL or to reload. Since it does not have any direct connection to executed page functions by you, you need to synchronize waiting to avoid race condition. You can also do it by using Promise.all():

Promise.all([
page.waitForNavigation({ waitUntil: ['load', 'networkidle2'] }),
page.click('<a link selector>'),
// or page.addScriptTag({ content: 'window.location = 'https://example.com;' })
]);

Don’t use it when your code does not trigger navigation because there is nothing to wait for, and you can reach timeout easily.

Or use an API

In case if you encounter this kind of errors when you take screenshots, this functionality is already built-in into the ScreenshotOne URL to Image API.

Behind the scenes wait_until and scripts_wait_until options are based on page.waitForNavigation().

The API is already scalable, reliable and battle-tested in production by paying customers.

And you can start using screenshot API for free.

Read more Puppeteer guides

Interviews, tips, guides, industry best practices, and news.

View all posts

Automate website screenshots

Exhaustive documentation, ready SDKs, no-code tools, and other automation to help you render website screenshots and outsource all the boring work related to that to us.