20

我使用 ws 端点 ( puppeteer.connect({ browserWSEndpoint: '' })) 连接到浏览器。

当我启动最终连接到的浏览器时,有没有办法以隐身方式启动它?

我知道我可以做这样的事情:

const incognito = await this.browser.createIncognitoBrowserContext();

但似乎隐身会话与最初打开的浏览器相关联。我只希望它独自存在。

我也看到你可以这样做:

const baseOptions: LaunchOptions = { args: ['--incognito']};

但我不确定这是否是最好的方法。

任何意见,将不胜感激。谢谢!

4

3 回答 3

35

实现目标的最佳方法是将浏览器直接启动到隐身模式,方法是将--incognito标志传递给puppeteer.launch()

const browser = await puppeteer.launch({
  args: [
    '--incognito',
  ],
});

或者,您可以在启动浏览器后使用以下命令创建新的隐身浏览器上下文browser.createIncognitoBrowserContext()

const browser = await puppeteer.launch();
const context = await browser.createIncognitoBrowserContext();

您可以使用以下方法检查浏览器上下文是否为隐身browserContext.isIncognito()

if (context.isIncognito()) { /* ... */ }
于 2018-08-29T05:47:03.550 回答
23

上面的解决方案对我不起作用:

创建了一个隐身窗口,但是当创建新页面时,它不再是隐身窗口。

对我有用的解决方案是:

const browser = await puppeteer.launch();
const context = await browser.createIncognitoBrowserContext();
const page = await context.newPage();

然后你可以使用页面,它是一个隐身页面

于 2019-07-01T03:02:01.473 回答
0

对于 Puppeteer 来说,它相当混乱,但这似乎有效.. 希望它可以帮助某人。

using (Browser browser = await Puppeteer.LaunchAsync(options))
{
     // create the async context 
    var context = await browser.CreateIncognitoBrowserContextAsync();

    // get the page created by default when launch async ran and close it whilst keeping the browser active
    var browserPages = await browser.PagesAsync();
    await browserPages[0].CloseAsync();

    // create a new page using the incognito context
    using (Page page = await context.NewPageAsync())
    {
        // do something 
    }
}
于 2020-04-14T17:10:55.267 回答