How to list all the cookies of the current page using JavaScript ?
Last Updated :
13 Sep, 2024
Cookies are small pieces of data stored by websites on your browser to remember information about your visit, such as login status, preferences, or other settings. In JavaScript, you can easily retrieve cookies stored by the current domain using document.cookie. However, due to security reasons, you can only access cookies set by the current domain and not those set by other domains.
We will learn how to get a list of all cookies for the current page in JavaScript through various approaches. We will explore three different methods to accomplish this task and provide examples to help you understand each approach.
Approach 1: Using document.cookie and .split()
In this approach, we will access cookies using document.cookie, which returns a string containing all cookies for the current domain. We then split this string on ";" to get an array of individual cookies, traverse through the array, and append each cookie to a string for display.
Steps:
- Access the cookies using document.cookie.
- Use the .split(";") method to split the cookies string into an array.
- Traverse the array to access each cookie.
- Append each cookie to a string for printing.
Example: This example implements the above approach.
JavaScript
function getCookies() {
let cookie = "username=geeks;expires=Mon, 18 Dec 2023;path=/";
let cookies = cookie.split(';');
let ret = '';
for (let i = 1; i <= cookies.length; i++) {
ret += i + ' - ' + cookies[i - 1] + "\n";
}
return ret;
}
console.log(getCookies());
Output1 - username=geeks
2 - expires=Mon, 18 Dec 2023
3 - path=/
Approach 2: Using document.cookie with .reduce()
This approach also starts by accessing the cookies using document.cookie and splitting them into an array using .split(";"). However, instead of manually appending the cookies, we use the .reduce() method to transform the cookies into a more structured format, such as an object with cookie names as keys and values as values.
- Access the cookies using document.cookie.
- Use the .split() method to split them on ";" to get an array of cookies.
- Use the .reduce() method and access each cookie one by one.
- To get the name and value of the cookie. For each cookie, split it on "=" using the .split() method and access the Name and Value from the cookie.
- This method does the same thing as the previous method and returns the cookies as an object.
Example: This example implements the above approach.
JavaScript
function getCookies() {
let cookie = "username=geeks;expires=Mon, 18 Dec 2023;path=/";
let cookies = cookie.split(';').reduce(
(cookies, cookie) => {
const [name, val] = cookie.split('=').map(c => c.trim());
cookies[name] = val;
return cookies;
}, {});
return cookies;
}
console.log(getCookies());
Output{ username: 'geeks', expires: 'Mon, 18 Dec 2023', path: '/' }
Approach 3: Using document.cookie with .map() and Object.fromEntries()
In this approach, we first access the cookies using document.cookie and split them into an array. We then use .map() to create an array of key-value pairs for each cookie. Finally, we transform this array into an object using Object.fromEntries().
- Access the cookies using document.cookie.
- Use the .split() method to split them on ; to get an array of cookies.
- Use the map() method to create an array of key-value pairs for each cookie.
- Transform the array of key-value pairs into an object using Object.fromEntries().
Example: Implementing the third approach
JavaScript
function getCookies() {
let cookie = "username=geeks;expires=Mon, 18 Dec 2023;path=/";
let cookies = Object.fromEntries(
cookie.split(';').map(cookie => {
const [name, val] = cookie.split('=').map(c => c.trim());
return [name, val];
})
);
return cookies;
}
console.log(getCookies());
Output{ username: 'geeks', expires: 'Mon, 18 Dec 2023', path: '/' }
Each approach provides a different way to handle and display cookies, giving you the flexibility to choose the method that best fits your needs.
Similar Reads
How to print the content of current window using JavaScript ?
The task is to print the content of the current window by using the window.print() method in the document. It is used to open the Print Dialog Box to print the current document. It does not have any parameter value. Syntax: window.print()Parameters: No parameters are requiredReturns: This function d
2 min read
How to Set & Retrieve Cookies using JavaScript ?
In JavaScript, setting and retrieving the cookies is an important task for assessing small pieces of data on a user's browser. This cookie can be useful for storing user preferences, session information, and many more tasks. Table of Content Using document.cookieUsing js-cookie libraryUsing document
2 min read
How to create cookie with the help of JavaScript ?
A cookie is an important tool as it allows you to store the user information as a name-value pair separated by a semi-colon in a string format. If we save a cookie in our browser then we can log in directly to the browser because it saves the user information. Approach: When a user sends the request
2 min read
How to Detect Operating System on the Client Machine using JavaScript?
To detect the operating system on the client machine, one can simply use navigator.appVersion property. The Navigator appVersion property is a read-only property and it returns a string that represents the version information of the browser. Syntax:navigator.appVersionExample 1: This example uses th
2 min read
How to Clear all Cookies using JavaScript?
Cookies allow clients and servers to exchange information via HTTP, enabling state management despite HTTP being a stateless protocol. When a server sends a response, it can pass data to the user's browser in the form of key-value pairs, which the browser stores as cookies. On subsequent requests to
2 min read
How to Get the Content of an HTML Comment using JavaScript ?
In this article, we will learn how to get the content of an HTML Comment Using Javascript. Comments are a best practice in programming and software development. In general, they can explain why a coding decision was made or what needs to be done to improve the code you're working on. HTML tags (incl
3 min read
How to get the file name from page URL using JavaScript ?
JavaScript provides multiple techniques for string manipulation and pattern matching. By demonstrating various methods, the article equips developers with versatile solutions to dynamically retrieve and utilize file names from different URL formats within their applications. There are several approa
3 min read
Display the number of links present in a document using JavaScript
Any webpage that is loaded in the browser can be represented by the Document interface. This serves as an entry point to the DOM tree and the DOM tree contains all elements such as <body> , <title>, <table> ,<a> etc. We can create a Document object using the Document() constr
2 min read
How to Get the Current URL using JavaScript?
Here are two different methods to get the current URL in JavaScript.1. Using Document.URL PropertyThe DOM URL property in HTML is used to return a string that contains the complete URL of the current document. The string also includes the HTTP protocol such as ( http://).Syntaxdocument.URLReturn Val
1 min read
How to get an object containing parameters of current URL in JavaScript ?
The purpose of this article is to get an object which contains the parameter of the current URL. Example: Input: www.geeksforgeeks.org/search?name=john&age=27 Output: { name: "john", age: 27 } Input: geeksforgeeks.org Output: {} To achieve this, we follow the following steps. Create an empty obj
2 min read