Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Docs: Browser cookies #1328

Merged
merged 12 commits into from
Sep 20, 2023
Original file line number Diff line number Diff line change
Expand Up @@ -10,17 +10,18 @@ The [browser module API](/javascript-api/k6-experimental/browser#browser-module-
If a [page](/javascript-api/k6-experimental/browser/page/) opens another page, e.g. with a `window.open` call, the popup will belong to the parent page's `BrowserContext`.


| Method | Description |
|-------------------------------------------------------------------------------------------------------------------------------------------------|------------------------------------------------------------------------------------------------------------|
| [BrowserContext.addCookies()](/javascript-api/k6-experimental/browser/browsercontext/addcookies/) | Adds cookies into the `BrowserContext`. |
| [BrowserContext.clearCookies()](/javascript-api/k6-experimental/browser/browsercontext/clearcookies/) <BWIPT id="442"/> | Clear the `BrowserContext`'s cookies. |
| [BrowserContext.clearPermissions()](/javascript-api/k6-experimental/browser/browsercontext/clearpermissions) <BWIPT id="443"/> | Clears all permission overrides for the `BrowserContext`. |
| [BrowserContext.close()](/javascript-api/k6-experimental/browser/browsercontext/close) | Close the `BrowserContext` and all its [page](/javascript-api/k6-experimental/browser/page/)s. |
| [BrowserContext.grantPermissions(permissions[, options])](/javascript-api/k6-experimental/browser/browsercontext/grantpermissions) | Grants specified permissions to the `BrowserContext`. |
| [BrowserContext.newPage()](/javascript-api/k6-experimental/browser/browsercontext/newpage) | Uses the `BrowserContext` to create a new [Page](/javascript-api/k6-experimental/browser/page/) and returns it. |
| [BrowserContext.pages()](/javascript-api/k6-experimental/browser/browsercontext/pages) <BWIPT id="444"/> | Returns a list of [page](/javascript-api/k6-experimental/browser/page/)s that belongs to the `BrowserContext`. |
| [BrowserContext.setDefaultNavigationTimeout(timeout)](/javascript-api/k6-experimental/browser/browsercontext/setdefaultnavigationtimeout) <BWIPT id="445"/> | Sets the default navigation timeout in milliseconds. |
| [BrowserContext.setDefaultTimeout(timeout)](/javascript-api/k6-experimental/browser/browsercontext/setdefaulttimeout) <BWIPT id="456"/> | Sets the default maximum timeout for all methods accepting a timeout option in milliseconds. |
| [BrowserContext.setGeolocation(geolocation)](/javascript-api/k6-experimental/browser/browsercontext/setgeolocation) <BWIPT id="435"/> | Sets the `BrowserContext`'s geolocation. |
| [BrowserContext.setOffline(offline)](/javascript-api/k6-experimental/browser/browsercontext/setoffline) | Toggles the `BrowserContext`'s connectivity on/off. |
| [BrowserContext.waitForEvent(event[, optionsOrPredicate])](/javascript-api/k6-experimental/browser/browsercontext/waitforevent) <BWIPT id="447"/> | Waits for the event to fire and passes its value into the predicate function. |
| Method | Description |
| ----------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------- |
| [BrowserContext.addCookies()](/javascript-api/k6-experimental/browser/browsercontext/addcookies/) | Adds [cookies](/javascript-api/k6-experimental/browser/browsercontext/cookie) into the `BrowserContext`. |
| [BrowserContext.clearCookies()](/javascript-api/k6-experimental/browser/browsercontext/clearcookies/) | Clear the `BrowserContext`'s [cookies](/javascript-api/k6-experimental/browser/browsercontext/cookie). |
| [BrowserContext.clearPermissions()](/javascript-api/k6-experimental/browser/browsercontext/clearpermissions) <BWIPT id="443"/> | Clears all permission overrides for the `BrowserContext`. |
| [BrowserContext.cookies()](/javascript-api/k6-experimental/browser/browsercontext/cookies) | Returns a list of [cookies](/javascript-api/k6-experimental/browser/browsercontext/cookie) from the `BrowserContext`. |
| [BrowserContext.close()](/javascript-api/k6-experimental/browser/browsercontext/close) | Close the `BrowserContext` and all its [page](/javascript-api/k6-experimental/browser/page/)s. |
| [BrowserContext.grantPermissions(permissions[, options])](/javascript-api/k6-experimental/browser/browsercontext/grantpermissions) | Grants specified permissions to the `BrowserContext`. |
| [BrowserContext.newPage()](/javascript-api/k6-experimental/browser/browsercontext/newpage) | Uses the `BrowserContext` to create a new [Page](/javascript-api/k6-experimental/browser/page/) and returns it. |
| [BrowserContext.pages()](/javascript-api/k6-experimental/browser/browsercontext/pages) <BWIPT id="444"/> | Returns a list of [page](/javascript-api/k6-experimental/browser/page/)s that belongs to the `BrowserContext`. |
| [BrowserContext.setDefaultNavigationTimeout(timeout)](/javascript-api/k6-experimental/browser/browsercontext/setdefaultnavigationtimeout) <BWIPT id="445"/> | Sets the default navigation timeout in milliseconds. |
| [BrowserContext.setDefaultTimeout(timeout)](/javascript-api/k6-experimental/browser/browsercontext/setdefaulttimeout) <BWIPT id="456"/> | Sets the default maximum timeout for all methods accepting a timeout option in milliseconds. |
| [BrowserContext.setGeolocation(geolocation)](/javascript-api/k6-experimental/browser/browsercontext/setgeolocation) <BWIPT id="435"/> | Sets the `BrowserContext`'s geolocation. |
| [BrowserContext.setOffline(offline)](/javascript-api/k6-experimental/browser/browsercontext/setoffline) | Toggles the `BrowserContext`'s connectivity on/off. |
| [BrowserContext.waitForEvent(event[, optionsOrPredicate])](/javascript-api/k6-experimental/browser/browsercontext/waitforevent) <BWIPT id="447"/> | Waits for the event to fire and passes its value into the predicate function. |
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,14 @@ title: 'addCookies()'
excerpt: 'Clears context cookies.'
---

Adds cookies into the `BrowserContext`. All pages within this context will have these cookies installed.
Adds a list of [cookies](/javascript-api/k6-experimental/browser/browsercontext/cookie) into the [BrowserContext](/javascript-api/k6-experimental/browser/browsercontext/cookie). All pages within this [BrowserContext](/javascript-api/k6-experimental/browser/browsercontext/cookie) will have these [cookies](/javascript-api/k6-experimental/browser/browsercontext/cookie) set.

<Blockquote mod="info">

If a [cookie](/javascript-api/k6-experimental/browser/browsercontext/cookie)'s `url` property is not provided, both `domain` and `path` properties must be specified.

</Blockquote>


### Example

Expand All @@ -27,18 +34,54 @@ export const options = {

export default async function () {
const context = browser.newContext();
const page = context.newPage();

context.addCookies([
{
name: 'myCookie',
value: 'hello world',
url: 'https://test.k6.io/',
},
]);
try {
const unixTimeSinceEpoch = Math.round(new Date() / 1000);
const day = 60*60*24;
const dayAfter = unixTimeSinceEpoch+day;
const dayBefore = unixTimeSinceEpoch-day;

const page = context.newPage();
await page.goto('https://test.k6.io/');
page.close();
context.addCookies([
// this cookie expires at the end of the session
{
name: 'testcookie',
value: '1',
sameSite: 'Strict',
domain: 'httpbin.org',
path: '/',
httpOnly: true,
secure: true,
},
// this cookie expires in a day
{
name: 'testcookie2',
value: '2',
sameSite: 'Lax',
domain: 'httpbin.org',
path: '/',
expires: dayAfter,
},
// this cookie expires in the past, so it will be removed.
{
name: 'testcookie3',
value: '3',
sameSite: 'Lax',
domain: 'httpbin.org',
path: '/',
expires: dayBefore
}
]);
ka3de marked this conversation as resolved.
Show resolved Hide resolved

const response = await page.goto('https://httpbin.org/cookies', {
waitUntil: 'networkidle',
});
console.log(response.json());
// prints:
// {"cookies":{"testcookie":"1","testcookie2":"2"}}
} finally {
page.close();
}
}
```

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,6 @@ title: 'clearCookies()'
excerpt: 'Clears context cookies.'
---

<Blockquote mod="attention">

This feature has **known issues**. For details, refer to
[#442](https://github.com/grafana/xk6-browser/issues/442).

</Blockquote>

Clears the `BrowserContext`'s cookies.

### Example
Expand All @@ -36,8 +29,11 @@ export default async function () {
const context = browser.newContext();
const page = context.newPage();

await page.goto('https://test.k6.io/');
await page.goto('https://httpbin.org/cookies/set?testcookie=testcookievalue');
console.log(context.cookies().length); // prints: 1

context.clearCookies();
console.log(context.cookies().length); // prints: 0
}
```

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
---
title: "Cookie"
excerpt: "Browser module: Cookie Class"
---

Cookie class represents a cookie in the [BrowserContext](/javascript-api/k6-experimental/browser/browsercontext).

See the [HTTP Cookies documentation](https://developer.mozilla.org/en-US/docs/Web/HTTP/Cookies) on the Mozilla website for more details about cookies.

| Property | Type | Default | Description |
| -------- | ------ | ------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| name | string | `""` | The cookie's name. Required. |
| value | string | `""` | The cookie's value. Required. |
| domain | string | `""` | The cookie's domain. |
| path | string | `'/'` | The cookie's path. |
| url | string | `""` | The cookie's URL. |
| expires | number | `-1` | The cookie's expiration date as the number of seconds since the UNIX epoch. `-1` means a session cookie. |
| httpOnly | bool | `false` | A cookie is inaccessible to the JavaScript [document.cookie](https://developer.mozilla.org/en-US/docs/Web/API/Document/cookie) API when this property is `true`. |
| secure | bool | `false` | The cookie's secure flag. |
| sameSite | string | `'Lax'` | The cookie's same site flag. It can be one of `'Strict'`, `'Lax'`, and `'None'`. |
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
---
title: 'cookies([urls])'
excerpt: 'Retrieves context cookies.'
---

Returns a list of [cookies](/javascript-api/k6-experimental/browser/browsercontext/cookie) from the [BrowserContext](/javascript-api/k6-experimental/browser/browsercontext) filtered by the provided `urls`. If no `urls` are provided, all cookies are returned.

| Parameter | Type | Description |
|----------------|--------|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| urls | array | A string array of URLs to filter the [cookies](/javascript-api/k6-experimental/browser/browsercontext/cookie) in the [BrowserContext](/javascript-api/k6-experimental/browser/browsercontext). |

### Returns

| Type | Description |
| ---- | ----------- |
| array | A list of [cookies](/javascript-api/k6-experimental/browser/browsercontext/cookie). |

<Blockquote mod="info">

[Cookies](/javascript-api/k6-experimental/browser/browsercontext/cookie) can be added with [BrowserContext.addCookies](/javascript-api/k6-experimental/browser/browsercontext/addcookies/).

</Blockquote>

### Example

<CodeGroup labels={[]}>

```javascript
import { browser } from 'k6/experimental/browser';

export const options = {
scenarios: {
ui: {
executor: 'shared-iterations',
options: {
browser: {
type: 'chromium',
},
},
},
},
};

export default async function () {
ankur22 marked this conversation as resolved.
Show resolved Hide resolved
const context = browser.newContext();
const page = context.newPage();

try {
// get cookies from the browser context
let cookies = context.cookies();
console.log("initial cookies length:", cookies.length); // prints 0

// let's add more cookies to filter by urls
context.addCookies([
{ name: 'foo', value: 'foovalue', sameSite: 'Strict', url: 'http://foo.com' },
{ name: 'bar', value: 'barvalue', sameSite: 'Lax', url: 'https://bar.com' },
{ name: 'baz', value: 'bazvalue', sameSite: 'Lax', url: 'https://baz.com' }
]);

// get all cookies
cookies = context.cookies();
console.log("filtered cookies length:", cookies.length); // prints 3

// get cookies filtered by urls
cookies = context.cookies('http://foo.com', 'https://baz.com');
console.log("filtered cookies length:", cookies.length); // prints 2

// the first filtered cookie
console.log("1st cookie's name :", cookies[0].name); // prints foo
console.log("1st cookie's value:", cookies[0].value); // prints foovalue
// the first filtered cookie
console.log("2nd cookie's name :", cookies[1].name); // prints baz
console.log("2nd cookie's value:", cookies[1].value); // prints bazvalue
} finally {
page.close();
}
}
```

</CodeGroup>