Skip to main content
Version: 23.10.1

Cookie

Puppeteer 提供了通过直接操作浏览器存储来提前获取、设置和删除 cookie 的方法。如果你需要为测试存储和恢复特定的 cookie,这将非常有用。

¥Puppeteer offers methods to get, set and delete cookies ahead of time by manipulating browser storage directly. This is useful if you need to store and restore specific cookies for your tests.

获取 cookies

¥Getting cookies

以下示例演示了如何在浏览器的默认 BrowserContext 中获取可用的 cookie。

¥The following example demonstrates how to get cookies available in the browser's default BrowserContext.

import puppeteer from 'puppeteer';

const browser = await puppeteer.launch();

const page = await browser.newPage();

await page.goto('https://example.com');

// In this example, we set a cookie using script evaluation.
// Cookies can be set by the page/server in various ways.
await page.evaluate(() => {
document.cookie = 'myCookie = MyCookieValue';
});

console.log(await context.cookies()); // print available cookies.

设置 cookies

¥Setting cookies

Puppeteer 还可以将 cookie 直接写入浏览器的存储中:

¥Puppeteer can also write cookies directly into the browser's storage:

import puppeteer from 'puppeteer';

const browser = await puppeteer.launch();

// Sets two cookies for the localhost domain.
await browser.setCookie(
{
name: 'cookie1',
value: '1',
domain: 'localhost',
path: '/',
sameParty: false,
expires: -1,
httpOnly: false,
secure: false,
sourceScheme: 'NonSecure',
},
{
name: 'cookie2',
value: '2',
domain: 'localhost',
path: '/',
sameParty: false,
expires: -1,
httpOnly: false,
secure: false,
sourceScheme: 'NonSecure',
},
);

console.log(await context.cookies()); // print available cookies.

删除 cookies

¥Deleting cookies

Browser.deleteCookie() 方法允许从存储中删除 cookie。

¥Browser.deleteCookie() method allows deleting cookies from storage.

除了在默认浏览器上下文上运行的 Browser 方法外,BrowserContext 类上也提供相同的方法。

¥In addition to the Browser methods operating on the default browser context, the same methods are available on the BrowserContext class.