我正在尝试使用 puppeteer 导航到页面,等待 webapp 达到特定状态,截屏并退出。当 SPA 处于我想要截屏的状态时,它会调用一个函数。我很难理解异步 js 代码。
我的代码如下所示:
const puppeteer = require('puppeteer');
const url = 'http://example.com/';
const width = 300;
const height = 250;
const path = '/vagrant/tmp/screenshot.jpg';
async function takeScreenshoot(url, width, height, path) {
"use strict";
const browser = await puppeteer.launch();
const page = await browser.newPage();
await page.setViewport({width: width, height: height});
await page.exposeFunction('interestingFunction', (async data => {
console.log('Interesting function has been called. Taking a screenshot now.');
await page.screenshot({path: path});
await browser.close();
}));
await page.goto(url);
}
(async () => {
"use strict";
await takeScreenshoot(url, width, height, path);
})();
但是当我打电话时screenshot.js
,我收到有关未处理承诺的警告,说“会话已关闭。很可能页面已关闭。”
node --trace-warnings screenshot.js
Interesting function has been called. Taking a screenshot now.
(node:2572) Error: Protocol error (Runtime.evaluate): Session closed. Most likely the page has been closed.
at Session.send (/vagrant/node_modules/puppeteer/lib/Connection.js:167:29)
at Page._onConsoleAPI (/vagrant/node_modules/puppeteer/lib/Page.js:296:20)
at <anonymous>
at process._tickCallback (internal/process/next_tick.js:188:7)
(node:2572) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
at emitWarning (internal/process/promises.js:78:15)
at emitPendingUnhandledRejections (internal/process/promises.js:95:11)
at process._tickCallback (internal/process/next_tick.js:189:7)
如果我await browser.close()
从第 18 行删除,没有警告,但脚本永远不会完成。
现在,它interstingFunction()
做了更多的事情,但是将它暴露在 webapp 的窗口中是安全的。我只是试图举一个上面仍然失败的最小脚本的例子。
我正在使用节点 v8.5.0。
我接近这个错误吗?