puppeteer 为 page.close() 安全地分离 CDP 会话

问题描述 投票:0回答:1

我有这个代码片段,与

puppeteer
一起使用来创建 CDP 会话。

let browser = await puppeteer.launch(options);
const page = await browser.newPage();
const session = await page.target().createCDPSession();

await session.send('Input.synthesizeScrollGesture', { 
                            x: 100,
                            y: 200,
                            yDistance: -150
                        });

当我在滚动发生时使用 page.close() 时,整个程序崩溃了

node_modules\puppeteer-core\lib\cjs\puppeteer\common\CallbackRegistry.js:73
            this._reject(callback, new Errors_js_1.TargetCloseError('Target closed'));
                                   ^

TargetCloseError: Protocol error (Input.synthesizeScrollGesture): Target closed
    at CallbackRegistry.clear 

或者这个错误

cdp\CDPSession.js:64
            return Promise.reject(new Errors_js_1.TargetCloseError(`Protocol error (${method}): Session closed. Most likely the ${this.#targetType} has been closed.`));
                                  ^

TargetCloseError: Protocol error (Network.getCookies): Session closed. Most likely the page has been closed.
    at CdpCDPSession.send (

我没有办法阻止这种情况,请帮忙。我想安全地分离并安全地关闭页面。

事实上,真正的问题是如何

page.close()
安全而不发生崩溃?

javascript node.js puppeteer
1个回答
0
投票

await session.detach()
帮我修好了。

您的代码抛出了 TargetCloseError,这意味着 Puppeteer 尝试与关闭的目标进行交互。我认为 Puppeteer 不会自动关闭 CDPSession。阅读 https://pptr.dev/api/puppeteer.cdpsession 了解更多信息。

let browser = await puppeteer.launch(options);
const page = await browser.newPage();
const session = await page.target().createCDPSession();

await session.send('Input.synthesizeScrollGesture', { 
    x: 100,
    y: 200,
    yDistance: -150
});

// Detach the CDPSession before closing the page
await session.detach();
await page.close();
await browser.close();
© www.soinside.com 2019 - 2024. All rights reserved.