How to avoid 'frame got detached' error as

2019-07-27 04:01发布

问题:

A previous answer pointed me into the direction, on how to catch an async validation error or redirect. But in my scenario an iframe comes into play and it's keeping me busy, all day. Some pointers into the right direction would be really helpfull, since I can't get it right, eventhough the error states clearly what goes wrong.

The scenario's:

  1. An input is left empty. A button is clicked inside an iframe and a validation error is returned from an async request
  2. An input has a value. A button is clicked inside an iframe and the user is redirected to a page stating "yaay".

The error that is thrown in the second scenario states waitForFunction failed: frame got detached. Which makes sense since the frame no longer exists... I found the frame.isDetached() but that still keeps throwing the same error. What am I missing or how can I use this method to make it work?

let frame = (await page.frames())[0];
...
for (let action of actions) {
    if (action.type === '...') {
        // ...
    }

    if (action.type === 'click') {
        frame.click("#btn");        

        // works for scenario 1 
        await Promise.race([
            page.waitForNavigation({ waitUntil: "networkidle2" }),
            // ERROR THROWN HERE FOR SCENARIO 2
            // `waitForFunction failed: frame got detached`

            // the line below doesn't seem to work as well...
            // frame.isDetached() ? Promise.resolve() : frame.waitForSelector(".error")
            frame.waitForSelector(".error"),
        ]);

        if (await frame.$(".error")) {
            // there was an error
        } else {
            // the page changed
           if (await page.waitForFunction('document.querySelector("body").innerText === "finished"')) {
            // yeeey 
           }
        }
    }

}