How to use getAllCookies method in Webdriverio

Best JavaScript code snippet using webdriverio-monorepo

Run Webdriverio automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

browser_getAllCookies.js

Source: browser_getAllCookies.js Github

copy
1/* Any copyright is dedicated to the Public Domain.
2 * http://creativecommons.org/publicdomain/zero/1.0/ */
3
4"use strict";
5
6const SJS_PATH = "/browser/remote/test/browser/network/sjs-cookies.sjs";
7
8const DEFAULT_HOST = "http://example.org";
9const ALT_HOST = "http://example.net";
10const SECURE_HOST = "https://example.com";
11
12const DEFAULT_URL = `${DEFAULT_HOST}${SJS_PATH}`;
13
14add_task(async function noCookiesWhenNoneAreSet({ client }) {
15  const { Network } = client;
16  const { cookies } = await Network.getAllCookies();
17  is(cookies.length, 0, "No cookies have been found");
18});
19
20add_task(async function noCookiesForPristineContext({ client }) {
21  const { Network } = client;
22  await loadURL(DEFAULT_URL);
23
24  try {
25    const { cookies } = await Network.getAllCookies();
26    is(cookies.length, 0, "No cookies have been found");
27  } finally {
28    Services.cookies.removeAll();
29  }
30});
31
32add_task(async function allCookiesFromHostWithPort({ client }) {
33  const { Network } = client;
34  const PORT_URL = `${DEFAULT_HOST}:8000${SJS_PATH}?name=id&value=1`;
35  await loadURL(PORT_URL);
36
37  const cookie = {
38    name: "id",
39    value: "1",
40  };
41
42  try {
43    const { cookies } = await Network.getAllCookies();
44    is(cookies.length, 1, "All cookies have been found");
45    assertCookie(cookies[0], cookie);
46  } finally {
47    Services.cookies.removeAll();
48  }
49});
50
51add_task(async function allCookiesFromMultipleOrigins({ client }) {
52  const { Network } = client;
53  await loadURL(`${ALT_HOST}${SJS_PATH}?name=users&value=password`);
54  await loadURL(`${SECURE_HOST}${SJS_PATH}?name=secure&value=password`);
55  await loadURL(`${DEFAULT_URL}?name=foo&value=bar`);
56
57  const cookie1 = { name: "foo", value: "bar", domain: "example.org" };
58  const cookie2 = { name: "secure", value: "password", domain: "example.com" };
59  const cookie3 = { name: "users", value: "password", domain: "example.net" };
60
61  try {
62    const { cookies } = await Network.getAllCookies();
63    cookies.sort((a, b) => a.name.localeCompare(b.name));
64    is(cookies.length, 3, "All cookies have been found");
65    assertCookie(cookies[0], cookie1);
66    assertCookie(cookies[1], cookie2);
67    assertCookie(cookies[2], cookie3);
68  } finally {
69    Services.cookies.removeAll();
70  }
71});
72
73add_task(async function secure({ client }) {
74  const { Network } = client;
75  await loadURL(`${SECURE_HOST}${SJS_PATH}?name=foo&value=bar&secure`);
76
77  const cookie = {
78    name: "foo",
79    value: "bar",
80    domain: "example.com",
81    secure: true,
82  };
83
84  try {
85    // Cookie returned for secure protocols
86    let result = await Network.getAllCookies();
87    is(result.cookies.length, 1, "The secure cookie has been found");
88    assertCookie(result.cookies[0], cookie);
89
90    // For unsecure protocols the secure cookies are also returned
91    await loadURL(DEFAULT_URL);
92    result = await Network.getAllCookies();
93    is(result.cookies.length, 1, "The secure cookie has been found");
94    assertCookie(result.cookies[0], cookie);
95  } finally {
96    Services.cookies.removeAll();
97  }
98});
99
100add_task(async function expiry({ client }) {
101  const { Network } = client;
102  const date = new Date();
103  date.setDate(date.getDate() + 3);
104
105  const encodedDate = encodeURI(date.toUTCString());
106  await loadURL(`${DEFAULT_URL}?name=foo&value=bar&expiry=${encodedDate}`);
107
108  const cookie = {
109    name: "foo",
110    value: "bar",
111    expires: Math.floor(date.getTime() / 1000),
112    session: false,
113  };
114
115  try {
116    const { cookies } = await Network.getAllCookies();
117    is(cookies.length, 1, "A single cookie has been found");
118    assertCookie(cookies[0], cookie);
119  } finally {
120    Services.cookies.removeAll();
121  }
122});
123
124add_task(async function session({ client }) {
125  const { Network } = client;
126  await loadURL(`${DEFAULT_URL}?name=foo&value=bar`);
127
128  const cookie = {
129    name: "foo",
130    value: "bar",
131    expiry: -1,
132    session: true,
133  };
134
135  try {
136    const { cookies } = await Network.getAllCookies();
137    is(cookies.length, 1, "A single cookie has been found");
138    assertCookie(cookies[0], cookie);
139  } finally {
140    Services.cookies.removeAll();
141  }
142});
143
144add_task(async function path({ client }) {
145  const { Network } = client;
146  const PATH = "/browser/remote/test/browser/";
147  const PARENT_PATH = "/browser/remote/test/";
148
149  await loadURL(`${DEFAULT_URL}?name=foo&value=bar&path=${PATH}`);
150
151  const cookie = {
152    name: "foo",
153    value: "bar",
154    path: PATH,
155  };
156
157  try {
158    console.log("Check exact path");
159    await loadURL(`${DEFAULT_HOST}${PATH}`);
160    let result = await Network.getAllCookies();
161    is(result.cookies.length, 1, "A single cookie has been found");
162    assertCookie(result.cookies[0], cookie);
163
164    console.log("Check sub path");
165    await loadURL(`${DEFAULT_HOST}${SJS_PATH}`);
166    result = await Network.getAllCookies();
167    is(result.cookies.length, 1, "A single cookie has been found");
168    assertCookie(result.cookies[0], cookie);
169
170    console.log("Check parent path");
171    await loadURL(`${DEFAULT_HOST}${PARENT_PATH}`);
172    result = await Network.getAllCookies();
173    is(result.cookies.length, 1, "A single cookie has been found");
174    assertCookie(result.cookies[0], cookie);
175
176    console.log("Check non matching path");
177    await loadURL(`${DEFAULT_HOST}/foo/bar`);
178    result = await Network.getAllCookies();
179    is(result.cookies.length, 1, "A single cookie has been found");
180    assertCookie(result.cookies[0], cookie);
181  } finally {
182    Services.cookies.removeAll();
183  }
184});
185
186add_task(async function httpOnly({ client }) {
187  const { Network } = client;
188  await loadURL(`${DEFAULT_URL}?name=foo&value=bar&httpOnly`);
189
190  const cookie = {
191    name: "foo",
192    value: "bar",
193    httpOnly: true,
194  };
195
196  try {
197    const { cookies } = await Network.getAllCookies();
198    is(cookies.length, 1, "A single cookie has been found");
199    assertCookie(cookies[0], cookie);
200  } finally {
201    Services.cookies.removeAll();
202  }
203});
204
205add_task(async function sameSite({ client }) {
206  const { Network } = client;
207  for (const value of ["Lax", "Strict"]) {
208    console.log(`Test cookie with SameSite=${value}`);
209    await loadURL(`${DEFAULT_URL}?name=foo&value=bar&sameSite=${value}`);
210
211    const cookie = {
212      name: "foo",
213      value: "bar",
214      sameSite: value,
215    };
216
217    try {
218      const { cookies } = await Network.getAllCookies();
219      is(cookies.length, 1, "A single cookie has been found");
220      assertCookie(cookies[0], cookie);
221    } finally {
222      Services.cookies.removeAll();
223    }
224  }
225});
226
Full Screen

Storage.js

Source: Storage.js Github

copy
1export const Storage = {
2	// 设置Cookie
3	// name: 为cookie的名字
4	// value: 为对应的值
5	// exp: 为过期时间  单位为毫秒   默认设置为2个小时的过期时间
6	setCookie (name, value, exp = 60 * 60 * 2 * 1000) {
7		let date = new Date()
8		date.setTime(date.getTime() + exp)
9		document.cookie = `${name}=${escape(value)};expires=${date.toGMTString()}`
10	},
11	// 获取Cookie
12	// name: 为cookie的名字
13	getCookie (name) {
14		if (name) {
15			let reg = new RegExp(`(^| )${name}=([^;]*)(;|$)`)
16			let arr = document.cookie.match(reg)
17			if (arr) {
18				// return arr[2]
19				return arr[2]
20			} else {
21				return null
22			}
23		} else {
24			let getAllCookies = []
25			if (document.cookie !== '') {
26				let arrCookie = document.cookie.split('; ')
27				for (let k in arrCookie) {
28					getAllCookies.push({
29						name: `${unescape(arrCookie[k].split('=')[0])}`,
30						value: `${unescape(arrCookie[k].split('=')[1])}`
31					})
32				}
33				return getAllCookies
34			} else {
35				return null
36			}
37		}
38	},
39	// 删除 Cookie
40	// name: 为cookie的名字
41	deleteCookie (name) {
42		let date = new Date()
43		date.setTime(date.getTime() - 1)  // 设置过期了
44		if (name) {
45			let cookieInfo = Storage.getCookie(name)
46			if (cookieInfo !== null) {
47				document.cookie = `${name}=${cookieInfo};expires=${date.toGMTString()}`
48			}
49		} else {
50			let getAllCookies = Storage.getCookie()
51			for (let k in getAllCookies) {
52				document.cookie = `${getAllCookies[k].name}=${getAllCookies[k].value};expires=${date.toGMTString()}`
53			}
54		}
55	}
56}
57
Full Screen

Accelerate Your Automation Test Cycles With LambdaTest

Leverage LambdaTest’s cloud-based platform to execute your automation tests in parallel and trim down your test execution time significantly. Your first 100 automation testing minutes are on us.

Try LambdaTest

Run JavaScript Tests on LambdaTest Cloud Grid

Execute automation tests with Webdriverio on a cloud-based Grid of 3000+ real browsers and operating systems for both web and mobile applications.

Test now for Free
LambdaTestX

We use cookies to give you the best experience. Cookies help to provide a more personalized experience and relevant advertising for you, and web analytics for us. Learn More in our Cookies policy, Privacy & Terms of service

Allow Cookie
Sarah

I hope you find the best code examples for your project.

If you want to accelerate automated browser testing, try LambdaTest. Your first 100 automation testing minutes are FREE.

Sarah Elson (Product & Growth Lead)