In my coding project involving Puppeteer, I have designed a generic "click" function and a "getHtml" function as part of a wrapper:
class Page {
....
async click(selector: string) {
await this.context.evaluate((querySelector, text) => {
const elem = document.querySelector(querySelector) as HTMLInputElement;
if (elem) {
elem.click();
}
}, selector);
}
async getHtml() {//
const html = await this.context.evaluate(() => {
return document.querySelector('html')?.innerHTML;
})
return html;
}
}
As observed, the click() method simply takes a querySelector and clicks on the located element.
However, there is an issue that arises when the element clicked initiates a navigation event, leading to subsequent functions encountering the following error:
Execution context was destroyed, most likely because of a navigation
For instance, if the user code contains commands like:
const page = new Page(...)
...
await page.click('someSelector')//If this selector points to a link, it triggers a navigation.
await page.getHtml()//This command then results in an error
Is there any way to determine if a navigation event is pending so that I could optionally wait for it within different functions?
Simply implementing waitForNavigation by default inside the click function is not viable, as it will cause the program to freeze if the click does not lead to navigation.