- Saved searches
- Use saved searches to filter your results more quickly
- License
- p/delete-all-cookies
- Name already in use
- Sign In Required
- Launching GitHub Desktop
- Launching GitHub Desktop
- Launching Xcode
- Launching Visual Studio Code
- Latest commit
- Git stats
- Files
- README.md
- About
- Clear All Cookies With JavaScript
- Delete All Cookies for the Current Domain Using JavaScript
- Related Article — JavaScript Cookies
- How to Clear All Cookies with JavaScript?
- Setting the Expiry Date of All Cookies to a Date Earlier than the Current Date-Time
- Conclusion
- Как удалить все Cookie сайта с помощью JavaScript
- Как выставить время жизни cookie так, чтобы оно было просрочено и кука удалилась
- Как удалить все куки из браузера с помощью JavaScript
- Почему некоторые куки не могут быть удалены из браузера с помощью JavaScript
Saved searches
Use saved searches to filter your results more quickly
You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.
Clear all cookies that affect the currently loaded web page
License
p/delete-all-cookies
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Name already in use
A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?
Sign In Required
Please sign in to use Codespaces.
Launching GitHub Desktop
If nothing happens, download GitHub Desktop and try again.
Launching GitHub Desktop
If nothing happens, download GitHub Desktop and try again.
Launching Xcode
If nothing happens, download Xcode and try again.
Launching Visual Studio Code
Your codespace will open once ready.
There was a problem preparing your codespace, please try again.
Latest commit
Git stats
Files
Failed to load latest commit information.
README.md
This library exposes a function to clear all cookies that affect the currently loaded web page.
This is accomplished by iteratively removing all cookies for the current path, then the parent path, and so on, for the current domain, parent domain, and so on, as well as cookies without explicit path and domain specification.
// in source: window.clearCookies = require('delete-all-cookies')(window) // ES 6: import deleteAllCookiesFactory from 'delete-all-cookies' window.clearCookies = deleteAllCookiesFactory(window) // then, in console: clearCookies()
Released under the MIT license.
The code is derived from several Stack Overflow answers to the question of clearing all cookies affecting the current web page.
About
Clear all cookies that affect the currently loaded web page
Clear All Cookies With JavaScript
This article will help you to clear all cookies using JavaScript.
Cookies allow clients and servers to communicate and transfer information over HTTP. It allows the client to persist state information even when using the stateless protocol HTTP.
- Information about the cookie is sent in HTTP request headers on each subsequent visit to the domain from the user’s browser.
- Information such as login information, consent, and other parameters improves and personalizes the user experience.
Delete All Cookies for the Current Domain Using JavaScript
The cookie attribute in the current document is used to change the attributes of a cookie purchased using the HTML DOM cookie attribute. The document.cookie returns a string of all semicolon-delimited cookies associated with the current document.
The code below shows how to delete cookies using JavaScript. The code is run on an online editor to demonstrate that the code can delete only cookies generated by your site.
html> head> meta charset="utf-8"> title> title> head> body> main> script type="text/javascript"> document.cookie = "username=shiv"; document.cookie = "CONSENT=YES+IN.en+20170903-09-0"; function displayCookies() var displayCookies = document.getElementById("display"); displayCookies.innerHTML = document.cookie; > function deleteAllCookies() 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) : cookie; document.cookie = name + "=;expires=Thu, 01 Jan 1970 00:00:00 GMT"; > > script> button onclick="displayCookies()">Display Cookiesbutton> button onclick="deleteAllCookies()">Delete Cookiesbutton> p id="display">p> main> body> html>
The code above has two limitations.
- Cookies with the HttpOnly flag set are not deleted because the HttpOnly flag disables JavaScript access to the cookie.
- Cookies set as path values are not deleted. (Although these cookies appear under Deleted , they cannot be deleted without specifying the same value for the installation path.)
When you click on Display Cookies , it will display the cookies.
You can also view the cookies in the inspector.
After clicking on Delete Cookies , it will delete it, and you have to again click on display cookies to see whether it is deleted or not.
You can also see in the inspector whether it is deleted or not.
Shiv is a self-driven and passionate Machine learning Learner who is innovative in application design, development, testing, and deployment and provides program requirements into sustainable advanced technical solutions through JavaScript, Python, and other programs for continuous improvement of AI technologies.
Related Article — JavaScript Cookies
How to Clear All Cookies with JavaScript?
Sometimes, we may clear all the cookies stored in the browser for the given site.
In this article, we’ll look at how to clear all cookies with JavaScript.
Setting the Expiry Date of All Cookies to a Date Earlier than the Current Date-Time
We can clear all cookies with JavaScript by setting the expiry date of each cookie to a date and time that’s earlier than the current time.
const deleteAllCookies = () => < const cookies = document.cookie.split(";"); for (const cookie of cookies) < const eqPos = cookie.indexOf("="); const name = eqPos >-1 ? cookie.substr(0, eqPos) : cookie; document.cookie = name + "=;expires=Thu, 01 Jan 1970 00:00:00 GMT"; > > deleteAllCookies()
We create the deleteAllCookies function that splits the document.cookie string.
Then we loop through each cookie within the cookies array.
And then we get the index of the = sign and remove the equal sign if it’s not there.
Then we add the expires=Thu, 01 Jan 1970 00:00:00 GMT string after it to remove the cookie by making it expire.
This won’t delete cookies with the HttpOnly flag set since the flag disables JavaScript’s access to the cookie.
It also won’t delete cookies that have a Path value set.
This is because we can’t delete it without specifying the same Path value with which it’s set.
Conclusion
We can clear some cookies from the browser by splitting the cookie string and then adding an expiry date to it that’s earlier than the current date and time.
Как удалить все Cookie сайта с помощью JavaScript
При работе с cookie на странице сайта с помощью JavaScript иногда требуется не просто посмотреть их список (как это сделать подробно описано в → этой статье), а удалить одну cookie или все куки, которые принадлежат сайту. Удаление cookie из браузера происходит следующим образом: если время жизни cookie истекает (или её дата хранения), браузер автоматически удаляет такие куки. Тут приходится положится на разработчиков браузеров, что они правильно заложили данный механизм удаления кук. Если присвоить нулевое значение хранящемуся параметру cookie, то это, скорее всего, не удалит куку из браузера, а всего лишь обнулит её значение.
Как выставить время жизни cookie так, чтобы оно было просрочено и кука удалилась
Небольшой экскурс в историю. Началом всех времён с точки зрения программиста является Четверг, 1 января 1970 года. Именно от этой даты принять отсчитывать время (причём в секундах). Всё, что было до этой даты, имеет отрицательное значение с точки зрения программистов.
Итак, чтобы убить куку в браузере, требуется выставить заведомо прошедшую дату. И для этого можно использовать дату Начала эпохи: Thu, 01 Jan 1970 00:00:00 GMT . На JavaScript это выглядит так:
document.cookie = "name=; expires=Thu, 01 Jan 1970 00:00:00 GMT;";
Именно параметр expires отвечает за хранение даты срока годности куки.
Но, можно попробовать обойтись тем, что большинство браузеров видя отрицательное значение expires , считают, что кука просрочена, и удаляют её. Т.е. ещё одним способом удалить cookie из браузера будет такой код:
document.cookie = "name=; expires=-1";
Я предпочитаю использовать более явный способ (который описан первым) и не рисковать тем, что разработчики браузера предусмотрели проверку на отрицательное значение дат.
Как удалить все куки из браузера с помощью JavaScript
Разобравшись с тем, как удалить куку из браузера, зная её имя, можно пробежаться по всему списку кук, доступному со страницы в браузере и выставить им просроченное время хранения:
function CookiesDelete() < 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) : cookie; document.cookie = name + "=;expires=Thu, 01 Jan 1970 00:00:00 GMT;"; document.cookie = name + '=; path=/; expires=Thu, 01 Jan 1970 00:00:01 GMT;'; > >
Обращаю внимание, что в данной функции есть две строчки удаления cookie в 7-й и в 8-й строках.
Дело в том, что я столкнулся с тем, что для удаления некоторых кук требуется не указывать путь в переменной path , а для некоторых, — требуется. Именно поэтому я использую оба варианта именно в такой последовательности. Это убивает куки напрочь.
Почему некоторые куки не могут быть удалены из браузера с помощью JavaScript
Ну и последний вопрос, касающийся удаления кук: «Почему некоторые куки не могут быть удалены из браузера с помощью JavaScript?»
Ответ прост, хотя лежит не совсем на поверхности. Куки могут задаваться не только с помощью JavaScript, но в и заголовках ответа сервера. И когда этот ответ приходит с флагом HttpOnly , данная кука перестаёт быть доступной для изменения с помощью JavaScript. Для удаления таких кук нужно либо лезть в настройки браузера и ручками их вычищать, либо лезть на сервер и генерировать страницу с очисткой кук по HTTP-протоколу.
Заберите ссылку на статью к себе, чтобы потом легко её найти!
Раз уж досюда дочитали, то может может есть желание рассказать об этом месте своим друзьям, знакомым и просто мимо проходящим?
Не надо себя сдерживать! 😉