puppeteer 在被破坏的上下文中评估结果

8 node.js es6-promise jestjs puppeteer

尝试等待 DOM 突变停止但以 结束Execution context was destroyed.,欢迎提出任何建议

            page.evaluate(() => {

                return new Promise((resolve,reject) => {

                    var timerId;

                    function resetTimer() {
                        clearInterval(timerId);
                        timerId = setTimeout(() => {
                            resolve(true);
                        }, 3000)
                    }

                    new MutationObserver(
                        () => {
                            resetTimer();
                        }
                    ).observe(document.getElementById('root'), {
                        attributes: true, childList: true
                    });

                    resetTimer();

                })
            })
        })
Run Code Online (Sandbox Code Playgroud)

协议错误 (Runtime.callFunctionOn):执行上下文被破坏。不明确的

  at Promise (node_modules/puppeteer/lib/Connection.js:198:56)
  at CDPSession.send (node_modules/puppeteer/lib/Connection.js:197:12)
  at ExecutionContext.evaluateHandle (node_modules/puppeteer/lib/ExecutionContext.js:71:75)
  at ExecutionContext.evaluate (node_modules/puppeteer/lib/ExecutionContext.js:46:31)
  at Frame.evaluate (node_modules/puppeteer/lib/FrameManager.js:299:20)
Run Code Online (Sandbox Code Playgroud)

小智 4

上面的代码片段是在页面上获得导航锁之前运行的。运行page.evaluate之间的导航可能会引发此错误。

发现这个来自,

  1. 错误:协议错误(Runtime.callFunctionOn):执行上下文已被破坏。
  2. 没有页面导航锁?

修复方法是(至少在我的情况下)等待 URL 更改,然后page.evaluate.