跳到主要内容

设置Cookie

为当前页面设置一个或多个cookies。确保你已经 在需要接收cookie的页面上。你不能在不访问该页面的情况下为任意页面设置cookie。

用法
browser.setCookies({ name, value, path, domain, secure, httpOnly, expiry, sameSite })
参数
名称类型详情
cookieArray<WebDriverCookie>, WebDriverCookiecookie对象或对象数组。
cookie.name
可选
Stringcookie的名称。
cookie.value
可选
Stringcookie的值。
cookie.path
可选
Stringcookie的路径。添加cookie时如果省略,默认为"/"。
cookie.domain
可选
Stringcookie可见的域。添加cookie时如果省略,默认为当前浏览上下文活动文档的URL域。
cookie.secure
可选
Booleancookie是否为安全cookie。添加cookie时如果省略,默认为false。
cookie.httpOnly
可选
Booleancookie是否为HTTP only cookie。添加cookie时如果省略,默认为false。
cookie.expiry
可选
Numbercookie过期时间,以Unix纪元以来的秒数指定。添加cookie时必须未设置如果省略。
cookie.sameSite
可选
Stringcookie是否应用于SameSite策略。添加cookie时如果省略,默认为None。可以设置为"Lax"或"Strict"。
示例
setCookies.js
it('should set a cookie for the page', async () => {
await browser.url('/')

// set a single cookie
await browser.setCookies({
name: 'test1',
value: 'one'
// The below options are optional
// path: '/foo', // The cookie path. Defaults to "/"
// domain: '.example.com', // The domain the cookie is visible to. Defaults to the current browsing context's active document's URL domain
// secure: true, // Whether the cookie is a secure cookie. Defaults to false
// httpOnly: true, // Whether the cookie is an HTTP only cookie. Defaults to false
// expiry: 1551393875 // When the cookie expires, specified in seconds since Unix Epoch
})

// set multiple cookies
await browser.setCookies([
{name: 'test2', value: 'two'},
{name: 'test3', value: 'three'}
])

const cookies = await browser.getCookies()
console.log(cookies);
// outputs:
// [
// {name: 'test1', value: 'one', domain: 'www.example.com'},
// {name: 'test2', value: 'two', domain: 'www.example.com'},
// {name: 'test3', value: 'three', domain: 'www.example.com'}
// ]
});

Welcome! How can I help?

WebdriverIO AI Copilot