木偶戏评估上下文中的结果被破坏

时间:2018-04-12 21:21:40

标签: node.js es6-promise jest 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();

                })
            })
        })

协议错误(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)

2 个答案:

答案 0 :(得分:0)

注意:

  • 您是否在代码中使用async / await?如果你有一个承诺,但不使用任何链或async / await,那么它应该抛出这样的错误。
  • 此外,您也正在通过观察者回调触发resetTimer。
  • 如果没有,那么您可能无法监控该dom元素的正确更改。

这是一个简单的反应应用程序,它会在2秒后改变状态。

class App extends Component {
  constructor() {
    super();
    this.state = { bar: "foo" };
  }

  componentDidMount() {
    setTimeout(() => this.setState({ bar: "not foo" }), 2000);
  }

  render() {
    return <div className="App">{this.state.bar}</div>;
  }
}

以下是上述代码段的修改代码。

 await page.evaluate(() => { // wait for it to resolve
    return new Promise((resolve, reject) => {
      var timerId;

      function resetTimer() {
        clearInterval(timerId);
        timerId = setTimeout(() => {
          resolve(true);
        }, 5000); // resolves after some time
      }
      const observer = new MutationObserver((mutations) => {
        // show me the changes
        mutations.forEach(function(mutation) {
            console.log(mutation.type);
        });
        // reset timer etc.
        resetTimer();
      });

      // observe a lot of changes
      observer.observe(document.getElementById("root"), {
        attributes: true,
        characterData: true,
        childList: true,
        subtree: true,
        attributeOldValue: true,
        characterDataOldValue: true
      });
    });
  });

结果如下: enter image description here

答案 1 :(得分:0)

上述代码段在获取页面上的导航锁之前运行。在导航之间运行page.evaluate可能会抛出此错误。

发现此事,

  1. Error: Protocol error (Runtime.callFunctionOn): Execution context was destroyed.
  2. No page navigation lock ?
  3. 修复(至少在我的情况下)等待URL更改,然后page.evaluate