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:
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()
:
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.