Home >Web Front-end >JS Tutorial >Day of DaysOfCode

Day of DaysOfCode

Patricia Arquette
Patricia ArquetteOriginal
2024-10-04 06:19:02335browse

Day of DaysOfCode

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.

What I wanted to achieve

  • Collect button elements on a specific webpage.
  • Click each buttons to navigate to another page.
  • After performing certain actions on the new page, go back to the first page.
  • Repeat Steps 2 and 3 until all buttons have been clicked.

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 */
    ]);
};

What error I encountered

After the forst loop iteration, the script wasn't able to locate the button elements. I kept getting the following error:
ProtocolError: Protocol error (DOM.describeNode): Cannot find context with specified id at

How I solved it

I resolved this issue by re-declaring the button elements list within the loop.
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 */
    ]);
};

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn