Clearing all cookies with javascript

How to Clear All Cookies with JavaScript?

Seal lying on rock covered with snow

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 или все куки, которые принадлежат сайту. Удаление cookie из браузера происходит следующим образом: если время жизни cookie истекает (или её дата хранения), браузер автоматически удаляет такие куки. Тут приходится положится на разработчиков браузеров, что они правильно заложили данный механизм удаления кук. Если присвоить нулевое значение хранящемуся параметру cookie, то это, скорее всего, не удалит куку из браузера, а всего лишь обнулит её значение.

Читайте также:  Pandas python read table

Небольшой экскурс в историю. Началом всех времён с точки зрения программиста является Четверг, 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-протоколу.

Заберите ссылку на статью к себе, чтобы потом легко её найти!
Раз уж досюда дочитали, то может может есть желание рассказать об этом месте своим друзьям, знакомым и просто мимо проходящим?
Не надо себя сдерживать! 😉

Читайте также:  Бот для бесед вк на питоне

Источник

Clearing all cookies with JavaScript

The cookie property of the current document is used to modify the attributes of the cookies buy using HTML DOM cookie Property . Question: How do you delete all the cookies for the current domain using JavaScript? Solution 1: Note that this code has two limitations: It will not delete cookies with flag set, as the flag disables Javascript’s access to the cookie.

Clearing all cookies with JavaScript

How do you delete all the cookies for the current domain using JavaScript?

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"; > > 

Note that this code has two limitations:

  • It will not delete cookies with HttpOnly flag set, as the HttpOnly flag disables Javascript’s access to the cookie.
  • It will not delete cookies that have been set with a Path value. (This is despite the fact that those cookies will appear in document.cookie , but you can’t delete it without specifying the same Path value with which it was set.)
One liner

In case you want to paste it in quickly.

document.cookie.split(";").forEach(function(c) < document.cookie = c.replace(/^ +/, "").replace(/=.*/, "=;expires=" + new Date().toUTCString() + ";path=/"); >); 

And the code for a bookmarklet :

And here’s one to clear all cookies in all paths and all variants of the domain (www.mydomain.com, mydomain.com etc):

After a bit of frustration with this myself I knocked together this function which will attempt to delete a named cookie from all paths. Just call this for each of your cookies and you should be closer to deleting every cookie then you were before.

function eraseCookieFromAllPaths(name) < // This function will attempt to remove a cookie from all paths. var pathBits = location.pathname.split('/'); var pathCurrent = ' path='; // do a simple pathless delete first. document.cookie = name + '=; expires=Thu, 01-Jan-1970 00:00:01 GMT;'; for (var i = 0; i < pathBits.length; i++) < pathCurrent += ((pathCurrent.substr(-1) != '/') ? '/' : '') + pathBits[i]; document.cookie = name + '=; expires=Thu, 01-Jan-1970 00:00:01 GMT;' + pathCurrent + ';'; >> 

As always different browsers have different behaviour but this worked for me. Enjoy.

Is my function of creating a cookie correct? How do I delete the cookie at the beginning of my program? is there a simple coding?

function createCookie(name,value,days) 
function setCookie(c_name,value,1) < document.cookie = c_name + "=" +escape(value); >setCookie('cookie_name',mac); function eraseCookie(c_name)
function delete_cookie( name, path, domain ) < if( get_cookie( name ) ) < document.cookie = name + "=" + ((path) ? ";path="+path:"")+ ((domain)?";domain="+domain:"") + ";expires=Thu, 01 Jan 1970 00:00:01 GMT"; >> 

You can define get_cookie() like this:

Here a good link on Quirksmode.

function setCookie(name,value,days) < var expires = ""; if (days) < var date = new Date(); date.setTime(date.getTime() + (days*24*60*60*1000)); expires = "; expires=" + date.toUTCString(); >document.cookie = name + "=" + (value || "") + expires + "; path=/"; > function getCookie(name) < var nameEQ = name + "="; var ca = document.cookie.split(';'); for(var i=0;i < ca.length;i++) < var c = ca[i]; while (c.charAt(0)==' ') c = c.substring(1,c.length); if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length); >return null; > function eraseCookie(name)

I know Max-Age causes the cookie to be a session cookie in IE when creating the cookie. Not sure how it works when deleting cookies.

Читайте также:  Java default что это

Some of the other solutions might not work if you created the cookie manually.

Here’s a quick way to delete a cookie:

document.cookie = 'COOKIE_NAME=; Max-Age=0; path=/; domain=' + location.host; 

If this doesn’t work, try replacing location.host with location.hostname in the snippet above.

Clearing all cookies with JavaScript, It also contains deleteAll method to clear all existing cookie. Make notice that this version of deleteAll method has setting path=/ that causes deleting of all cookies within current domain. If you need to delete cookies only from some scope you will have to upgrade this method my adding dynamic path parameter to this method. There is main Code samplefunction deleteAllCookies()

How to clear all cookies using JavaScript ?

Cookies provide a way for a client and server to interact and pass information via HTTP. This enables the client to store state information despite using HTTP which is a stateless protocol. When a browser requests a web page from a server, the server services the request and “forgets” about the visit. But it passes some information to the user’s browser. The browser stores the information in the form of key=value pairs and also manages this information.

  • Cookie information is passed in the HTTP request header during every subsequent visit to the domain from the user’s browser.
  • Information like login details, consent, other preferences are used to enhance and customize the user experience.

HTTP cookies expire, the date and time are specified in the “expires” attribute. As a result, the browser automatically deletes the cookies when the date and time exceed the expiration date (and time). As this attribute is configurable*, it is possible to delete all the cookies by setting the “expiry” to any value that has already passed.

The cookie property of the current document is used to modify the attributes of the cookies buy using HTML DOM cookie Property . The document.cookie returns a single string of all the cookies separated by semicolons associated with the current document.

Code: The code below illustrates how cookies can be deleted using JavaScript. The code is run on an online editor to demonstrate that only cookies created by your site can be deleted by the code.

Источник

Оцените статью