setCookies
為目前頁面設定一個或多個Cookie。請確保您位於應接收 Cookie 的頁面上。您無法在未位於該頁面的情況下為任意頁面設定 Cookie。
用法
browser.setCookies({ name, value, path, domain, secure, httpOnly, expiry, sameSite })
參數
名稱 | 類型 | 詳細資訊 |
---|---|---|
cookie | Array<WebDriverCookie> , WebDriverCookie | Cookie 物件或物件陣列。 |
cookie.name 選填 | 字串 | Cookie 的名稱。 |
cookie.value 選填 | 字串 | Cookie 的值。 |
cookie.path 選填 | 字串 | Cookie 的路徑。如果新增 Cookie 時省略,則預設為 "/"。 |
cookie.domain 選填 | 字串 | Cookie 可見的網域。如果新增 Cookie 時省略,則預設為目前瀏覽內容作用中文件的 URL 網域。 |
cookie.secure 選填 | 布林值 | Cookie 是否為安全 Cookie。如果新增 Cookie 時省略,則預設為 false。 |
cookie.httpOnly 選填 | 布林值 | Cookie 是否為僅限 HTTP 的 Cookie。如果新增 Cookie 時省略,則預設為 false。 |
cookie.expiry 選填 | 數字 | Cookie 過期的時間,以 Unix Epoch 之後的秒數指定。如果新增 Cookie 時省略,則不得設定。 |
cookie.sameSite 選填 | 字串 | Cookie 是否適用於 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'}
// ]
});