Reputation: 153
I am in a situation where I need my functional browser tests to check the returned status code of all page responses, and if I get a 503, attempt to reload the page X number of times before failing.
I have attempted to use Playwright network events, but it seems that altering the Page state (i.e. triggering a reload) breaks any future interaction and you end up with Execution context was destroyed, most likely because of a navigation.
errors.
For example:
page.on('response', async (response) => {
if (response.request().resourceType() !== 'document') return;
if (response.status() === 503) {
await page.reload();
}
}
(I have ommitted the retry attempts logic for simlicity)
After this code has executed, any attempts to interact with the page will result in the Execution context was destroyed
error.
I'm not 100% sure this is the right way to approach this problem. Any ideas?
Upvotes: 4
Views: 29501
Reputation: 11
it's working fine to me when I have written
await page.reload({waitUntil:'load'});
Upvotes: 1
Reputation: 2563
For me this part only was needed when searching for how to reload the page with Playwright:
await page.reload();
Upvotes: 5
Reputation: 2819
This is an interesting scenario. If response
was available at BrowserContext, your approach would work. Since that is not the case, "reload" needs to be done via opening a new page.
This can be achieved with a helper method that "returns page after retries". This method would retry page creation and navigation for error status code.
const {chromium} = require('playwright');
const pageAfterRetries = async (context, url, maxRetries) => {
if (!maxRetries) return;
const page = await context.newPage();
const [_, response] = await Promise.all([
page.goto(url),
page.waitForEvent('response', response => response.request().resourceType() === 'document')
]);
if (response.status() === 503) {
// Retry if this happens
await page.close();
return pageAfterRetries(context, url, maxRetries - 1);
}
return page;
}
(async() => {
const browser = await chromium.launch({headless: false});
const context = await browser.newContext();
const page = await pageAfterRetries(context, 'https://www.google.com', 3);
// Use page for remaining script
console.log(page);
})();
Upvotes: 4