Skip to content

Commit c3ab501

Browse files
inancgumuska3de
authored andcommitted
Update addCookies
1 parent 64de336 commit c3ab501

File tree

1 file changed

+47
-11
lines changed
  • src/data/markdown/docs/02 javascript api/07 k6-experimental/01 browser/02 BrowserContext

1 file changed

+47
-11
lines changed

src/data/markdown/docs/02 javascript api/07 k6-experimental/01 browser/02 BrowserContext/addCookies.md

Lines changed: 47 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,14 @@ title: 'addCookies()'
33
excerpt: 'Clears context cookies.'
44
---
55

6-
Adds cookies into the `BrowserContext`. All pages within this context will have these cookies installed.
6+
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) installed.
7+
8+
<Blockquote mod="info">
9+
10+
If a [cookie](/javascript-api/k6-experimental/browser/browsercontext/cookie)'s `url` property is not provided, both `domain` and `path` properties must be specified.
11+
12+
</Blockquote>
13+
714

815
### Example
916

@@ -27,18 +34,47 @@ export const options = {
2734

2835
export default async function () {
2936
const context = browser.newContext();
37+
const page = context.newPage();
3038

31-
context.addCookies([
32-
{
33-
name: 'myCookie',
34-
value: 'hello world',
35-
url: 'https://test.k6.io/',
36-
},
37-
]);
39+
try {
40+
const unixTimeSinceEpoch = Math.round(new Date() / 1000);
41+
const day = 60*60*24;
42+
const dayAfter = unixTimeSinceEpoch+day;
43+
const dayBefore = unixTimeSinceEpoch-day;
3844

39-
const page = context.newPage();
40-
await page.goto('https://test.k6.io/');
41-
page.close();
45+
context.addCookies([
46+
// this cookie expires at the end of the session
47+
{
48+
name: 'testcookie',
49+
value: '1',
50+
sameSite: 'Strict',
51+
domain: '127.0.0.1',
52+
path: '/',
53+
httpOnly: true,
54+
secure: true,
55+
},
56+
// this cookie expires in a day
57+
{
58+
name: 'testcookie2',
59+
value: '2',
60+
sameSite: 'Lax',
61+
domain: '127.0.0.1',
62+
path: '/',
63+
expires: dayAfter,
64+
},
65+
// this cookie expires in the past, so it will be removed.
66+
{
67+
name: 'testcookie3',
68+
value: '3',
69+
sameSite: 'Lax',
70+
domain: '127.0.0.1',
71+
path: '/',
72+
expires: dayBefore
73+
}
74+
]);
75+
} finally {
76+
page.close();
77+
}
4278
}
4379
```
4480

0 commit comments

Comments
 (0)