Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to clear all cookies with JavaScript?
In this tutorial, we will learn to clear all cookies using JavaScript. Cookies are text data stored in the browser that help websites remember user information like usernames, authentication tokens, and preferences.
When a user visits a webpage for the first time, it retrieves user information from the server and stores it as cookies in the browser. On subsequent visits, the webpage can access this stored data instead of making server requests, making the application faster and more efficient.
Modern browsers typically allow cookies up to 4KB in size, with limits on the total number: Chrome allows around 180 cookies per domain, while Firefox allows about 150.
How Cookie Clearing Works
To clear cookies in JavaScript, we set their expiration date to a past time. When a cookie's expiry date has passed, the browser automatically removes it.
Syntax
// Get all cookies
var cookies = document.cookie.split(';');
// Set past expiry date for each cookie
for (var i = 0; i < cookies.length; i++) {
document.cookie = cookies[i] + "=; expires=" + new Date(0).toUTCString();
}
Algorithm
Step 1 ? Get all cookies using
document.cookieStep 2 ? Split cookies string by ';' delimiter to get individual cookies
Step 3 ? Loop through each cookie and set its expires attribute to January 1, 1970
Complete Example
Below is a working example with buttons to show and clear cookies. A sample cookie is automatically created when the page loads.
<html>
<head>
<title>Clear Cookies Example</title>
</head>
<body>
<h2>Clear All Cookies with JavaScript</h2>
<h4>Click the buttons below to show and clear cookies</h4>
<button onclick="showCookies()">Show Cookies</button>
<button onclick="deleteCookies()">Clear Cookies</button>
<div id="show"></div>
<script>
// Function to display current cookies
function showCookies() {
var show = document.getElementById("show");
show.innerHTML = "<p>Current cookies: " + document.cookie + "</p>";
}
// Function to clear all cookies
function deleteCookies() {
var cookies = document.cookie.split(';');
// Set expiry date to January 1, 1970 for all cookies
for (var i = 0; i < cookies.length; i++) {
document.cookie = cookies[i] + "=; expires=" + new Date(0).toUTCString();
}
showCookies(); // Refresh display
}
// Set sample cookies when page loads
window.onload = function() {
let sampleData = { name: "TutorialsPoint", site: "tutorialspoint.com" };
document.cookie = 'sampleObject=' + JSON.stringify(sampleData);
document.cookie = 'username=johnDoe';
document.cookie = 'theme=dark';
showCookies(); // Show initial cookies
}
</script>
</body>
</html>
Enhanced Method with Domain and Path
For more thorough cookie clearing, especially cookies with specific domains or paths, use this enhanced approach:
function clearAllCookies() {
var cookies = document.cookie.split(';');
for (var i = 0; i < cookies.length; i++) {
var cookie = cookies[i];
var eqPos = cookie.indexOf('=');
var name = eqPos > -1 ? cookie.substr(0, eqPos).trim() : cookie.trim();
// Clear cookie for current path
document.cookie = name + '=;expires=Thu, 01 Jan 1970 00:00:00 GMT;path=/';
// Clear cookie for domain
document.cookie = name + '=;expires=Thu, 01 Jan 1970 00:00:00 GMT;path=/;domain=' + window.location.hostname;
// Clear cookie for parent domain
document.cookie = name + '=;expires=Thu, 01 Jan 1970 00:00:00 GMT;path=/;domain=.' + window.location.hostname;
}
}
// Test the enhanced method
document.cookie = "testCookie=value;path=/";
console.log("Before:", document.cookie);
clearAllCookies();
console.log("After:", document.cookie);
Key Points
Setting
expiresto a past date removes cookies immediatelynew Date(0)represents January 1, 1970 (Unix epoch)Some cookies may require specific domain and path parameters to be cleared
HttpOnly cookies cannot be cleared via JavaScript - only server-side
Conclusion
Clearing cookies in JavaScript involves setting their expiration date to a past time using document.cookie. This method works for all cookies accessible to JavaScript, making it useful for user logout functionality and privacy features.
