javascript - How to handle puppeteer exception on synchronous execution
问题描述
I am trying to achieve a synchronous call:
puppeteer.launch().then(browser => {
let html = `
<!DOCTYPE html>
<html>
<body>
<div>
Hello
</div>
</body>
</html>
`;
let path = 'test.png';
browser.newPage().then(page => {
page.setContent(html).then(() => {
page
.screenshot({
path: path,
clip: {
x: 50,
y: 50,
width: 100,
height: 100
},
omitBackground: true
})
.then(() => {});
});
});
browser.close().then(() => {});
});
I get the following exception:
(node:22140) UnhandledPromiseRejectionWarning: Error: Protocol error (Target.createTarget): Target closed. at Promise (C:\ImageServer\node_modules\puppeteer\lib\Connection.js:74:56) at new Promise () at Connection.send (C:\ImageServer\node_modules\puppeteer\lib\Connection.js:73:12) at Browser._createPageInContext (C:\ImageServer\node_modules\puppeteer\lib\Browser.js:174:47) at BrowserContext.newPage (C:\ImageServer\node_modules\puppeteer\lib\Browser.js:367:26) at Browser.newPage (C:\ImageServer\node_modules\puppeteer\lib\Browser.js:166:33) at Browser. (C:\ImageServer\node_modules\puppeteer\lib\helper.js:112:23) at puppeteer.launch.then.browser (C:\ImageServer\imageServer.js:48:12) at process._tickCallback (internal/process/next_tick.js:68:7) (node:22140) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1) (node:22140) [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.
How do I fix this?
解决方案
问题是您在browser.newPage
. 你应该移动browser.close()
到then
你所拥有的screenshot
。
page
.screenshot({
path: path,
clip: {
x: 50,
y: 50,
width: 100,
height: 100
},
omitBackground: true
})
.then(() => browser.close());
推荐阅读
- node.js - 如何编写 powershell 脚本来在 Windows 上设置开发人员环境?
- java - WearableRecyclerView Android Wear OS
- git - 为什么“无更改”的文件会出现在拉取请求中?
- python - Keras Tensorflow Graph 在 GPU 和 CPU 之间拆分
- php - PHP-FPM 不能使用 OCI 但是 PHP 是
- python - 你如何检查一个 typeshed stub (.pyi) 文件是否与实现匹配?
- delphi - 将 Delphi 的 Format() 函数视为 wsprintf() 的替代方法是否正确?
- c# - 使用 REST API v3 使用 C# 导出 Google Apps 脚本项目
- c - 稳健准确地计算两个浮点数的商的自然对数
- json - 对网站用户隐藏 JSON 文件并在 Android 应用程序中调用它