Hey! It's been a while since last entry.
Recently, I've been tackling an issue related to losing element references within a loop, and I finally found a solution that I'd like to share with you all.
Here's a simplified version of the initial code:
const someElements = await page.$$("xpath/ .//foo[@name='hoge']"); for (let i=0; i < someElements.length; i++) { await Promise.all([ someElements[i].click(), page.waitForNavigation({ waitUntil: ["load", 'networkidle0'] }), /* There are particular processes and going back process */ ]); };
After the forst loop iteration, the script wasn't able to locate the button elements. I kept getting the following error: I resolved this issue by re-declaring the button elements list within the loop. I added re-declaration line because I assumed the original someElements reference was getting lost when navigating away from the initial page. After this change, the error was resolved. However, I'm not sure if this approach strictly adheres to best coding practices. If you encounter an issue with .click() in a loop when navigating between pages, consider re-declaring the element within the loop itself. This simple change might save you a lot of troubleshooting time! The above is the detailed content of Day of DaysOfCode. For more information, please follow other related articles on the PHP Chinese website!
ProtocolError: Protocol error (DOM.describeNode): Cannot find context with specified id at
How I solved it
Here's the modified code:
const someElements1 = await page.$$("xpath/ .//foo[@name='hoge']");
for (let i=0; i < someElements.length; i++) {
const someElements2 = await page.$$("xpath/ .//foo[@name='hoge']"); // added row
await Promise.all([
someElements2[i].click(),
page.waitForNavigation({ waitUntil: ["load", 'networkidle0'] }),
/* There are particular processes and going back process */
]);
};