问题
I'm looking for a "best practice" (besides "don't do that") when using Puppeteer with a page that may (but not always) reload when a radio button is clicked, a select option is selected, etc. The use case is I'm navigating an eCommerce page with options, and some of those options cause the page to reload, some of them don't.
I've tried hooking into the on("load") event to try and catch when this happens, and reset my page variable, but I can't get the "timing" correct, and still end up with execution context exceptions. What I've resorted to is try/catching the execution context exceptions in a loop so I can retry. Below is sort of what I'm talking about, and I'm in violent hatred of it (it's ugly, verbose, etc.):
async evaluate(fn: EvaluateFn, ...args: any[]): Promise<any> {
let result: ElementHandle | null = null;
let page: Page | undefined = undefined;
for(let attempt = 0; attempt < this.MAX_EXECUTION_RETRIES; attempt++) {
try {
if(page == undefined) {
// this.browser is an earlier instantiate instance of a Puppeteer Browser
const pages = await this.browser.pages();
page = pages[pages.length = 1];
}
result = await page.evaluate(fn, ...args);
break;
} catch(e) {
if(attempt < this.MAX_EXECUTION_RETRIES - 1 && (e.message && e.message.indexOf("Execution context") != -1)) {
await sleep(this.EXECUTION_RETRY_DELAY);
page = undefined;
} else {
throw e;
}
}
}
return result;
}
Is there a better way to get notified or check if my page variable's execution context is no longer valid?
来源:https://stackoverflow.com/questions/61753901/detecting-navigation-with-puppeteer