首页 > 解决方案 > 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?

标签: javascriptnode.jses6-promisepuppeteer

解决方案


问题是您在browser.newPage. 你应该移动browser.close()then你所拥有的screenshot

page
    .screenshot({
        path: path,
        clip: {
            x: 50,
            y: 50,
            width: 100,
            height: 100
        },
        omitBackground: true
    })
    .then(() => browser.close());

推荐阅读