简体   繁体   中英

Javascript edit cookie's part value on click and reload page

I'm trying to change the content of a cookie when the user click on a button, and refresh the page after this. My cookie is named cookieConsent and has the content {"isCookieBarHidden":true,"cookiePreferences":{"functional":true,"userPreferences":true,"analytics":true,"advertisements":true}}

I'm trying to change "isCookieBarHidden":true to false on click on a button with an id, and reload the page after to display again the cookiebar of a website.

Is it possible to do this with pure Javascript ? If not, how in jquery ?

You can change a cookie's content the same way that you set it. Just assign new values to it and it should overwrite the old one. But if you have a cookie with a lot of properties, you can just use the includes() method to check the cookie's current isCookieBarHidden value and then based on that retrieved value, you can use the replace() method to change it's value to false or even better, toggle between true and false accordingly then reload the page like this:

if (document.cookie.includes('"isCookieBarHidden":true')) {
   document.cookie = document.cookie.replace('"isCookieBarHidden":true', '"isCookieBarHidden":false');
} else {
    document.cookie = document.cookie.replace('"isCookieBarHidden":false', '"isCookieBarHidden":true');
}

Check the Code Snippet below for a practical example of what I have described above:

 document.cookie = 'cookieConsent = {"isCookieBarHidden":true,"cookiePreferences":{"functional":true,"userPreferences":true,"analytics":true,"advertisements":true}}'; var dc = document.cookie; function alertCookie() { alert(dc); } function toggleCookie() { if (document.cookie.includes('"isCookieBarHidden":true')) { document.cookie.replace('"isCookieBarHidden":true', '"isCookieBarHidden":false'); } else { document.cookie.replace('"isCookieBarHidden":false', '"isCookieBarHidden":true'); } location.reload(); } document.getElementById("toggleCookie").addEventListener("click", toggleCookie); document.getElementById("alertCookie").addEventListener("click", alertCookie); 
 <!-- HTML --> <button id="toggleCookie">Toggle Cookie</button> <button id="alertCookie">Show cookies</button> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM