I have one requirement, at the time of pageloading I'm setting cookie using sessionStorage, once refresh/reload the page I have to delete the cookie.
I tried with the following code, but cookie is not deleting for reload the page,
Can someone help me please,
$(document).ready(function() {
$('#example').dataTable({
"bStateSave": true,
"fnStateSave": function (oSettings, oData) {
sessionStorage.setItem('POSummary', JSON.stringify(oData));
},
"fnStateLoad": function (oSettings) {
return JSON.parse(sessionStorage.getItem('POSummary'));
}
});
} );
Thanks
if you want delete a sessionStorage element you need to do this:
sessionStorage.removeItem("session-name");
if(sessionStorage.getItem('POSummary') != null)
sessionStorage.removeItem("POSummary");
if you want use cookie instead you must implement this two function:
function create (name, value, days){
var expires;
if (days) {
var date = new Date();
date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
expires = "; expires=" + date.toGMTString();
} else {
expires = "";
}
document.cookie = escape(name) + "=" + escape(value) + expires + "; path=/";
}
function erase (name){
create(name, "", -1);
}
Related
I have a button that should write a cookie once it's clicked and change button's textContent
<button id="menu-icon" onclick="writeCookie()">volume_up</button>
But it would write cookie only if I click it two times.
function createCookie(name,value,days) {
if (days) {
var date = new Date();
date.setTime(date.getTime() + (days * 24 * 60 * 60 *1000));
var expires = "; expires=" + date.toGMTString();
} else {
var expires = "";
}
document.cookie = name + "=" + value + expires + "; path=/";
}
function writeCookie(){
let element = document.querySelector("#menu-icon")
let state = element.textContent;
switch(state) {
case 'volume_off':
element.textContent = 'volume_up'
createCookie("default", "", -1)
createCookie("default", true, 100)
break;
case 'volume_up':
element.textContent = 'volume_off'
createCookie("default", "", -1)
createCookie("default", false, 100)
break;
}
}
How can I fix it?
Remove the onclick="writeCookie() from the html and add the following line in the js file.
document.document.getElementById("menu-icon").addEventListener("click", writeCookie);
You should also check the console log.
This can happen because your page is not fully loaded or element wrongly initialized.
If you are using jquery try on() method
<button id="menu-icon" >volume_up</button>
<script>
$(document).ready(function(){
$("#menu-icon").on("click",function(){
writeCookie();
});
});
</script>
I'm definitely new to Javascript, but I need to implement a tag within GTM to update 2 cookie values to 6 months for any unique user after the are loaded on the page.
I have the following script to alter the expiration date:
<script>
function getCookie(name) {
var value = "; " + document.cookie;
var parts = value.split("; " + name + "=");
if (parts.length == 2)
return parts.pop().split(";").shift();
}
var date = new Date();
date.setTime(date.getTime()+(365*24*60*60*1000));
var expires = "; expires="+date.toGMTString();
console.log("expires: " + expires);
var cookieName = "CookieA";
var OABCcookieName = "CookieB";
function updateCookieExpiration() {
var cookie = getCookie(cookieName);
document.cookie = cookieName + "=" + cookie + expires + ";path=/; Samesite=Lax;" //domain=" + domain + ";";
var OABCcookie = getCookie(OABCcookieName);
document.cookie = OABCcookieName + "=" + OABCcookie + expires + ";path=/; Samesite=Lax;" //domain=" + domain + ";";
}
</script>
My question is, if I add the following script, update 365 to 180, and call the updateCookieExpiration() function - won't the function be called on every page and cause the cookie expiration to always reset to 6 months?
If so, is there additional logic that I need to add to make sure the cookie expiration hasn't already been reset for a unique visitor, to avoid the scenario described?
Any help troubleshooting would be great and very appreciated!
You could add a condition check if the Cookie name already exist:
// You may prefer using max-age here
const sixMonthMaxAge = 60 * 60 * 24 * 180;
var newCookieName = "CookieA";
function updateCookieExpiration() {
const cookie = getCookie(cookieName);
// If cookie doesn't exist
if(!cookie) {
document.cookie = cookieName + "=" + cookie + ";" + "max-age=" sixMonthMaxAge + ";"
}
}
Using js-cookie library
Using library that abstract Cookie management can be a good idea, even more if you have to manager multiple cookies.
import Cookies from 'js-cookie'
const sixMonthMaxAge = 180; // You can provide the max-age in days
var newCookieName = "CookieA";
function updateCookieExpiration() {
const cookie = Cookies.get(cookieName);
if(!cookie) {
Cookie.set(cookieName, 'your_value', { expires: sixMonthMaxAge })
}
}
Cookies.set('foo', 'bar')
I'm setting up a new pop up and would like to create cookie. The basic function is to add classes into the wrapper if a cookie exists (or depending on value if that's possible). This is what I got so far:
HTML:
<div id="new-popup" class="active ">
<span class="collapse-popup">X</span>
<form>
<input class="tnp-email" type="email" placeholder="Email Address" name="ne" required="">
<input class="tnp-submit" type="submit" value="Submit">
</form>
</div>
JS/JQUERY:
jQuery(document).ready(function($) {
var popuptwo = $('#new-popup');
var cookie = GetCookie("testbb2020");
if(cookie == null) { }
if(cookie === 'closed') {
$('#new-popup').addClass('closed-test')
}
if(cookie === 'subscribed') {
$('#new-popup').addClass('subscribed-test')
}
// Click on "Close"
$('#new-popup .collapse-popup').click(function(event) {
var date = new Date();
date.setTime(date.getTime() + (30 * 24 * 60 * 60 * 1000));
expires = "; expires=" + date.toGMTString();
document.cookie = "testbb2020=closed" + expires + "; path=/"; {
}
});
// Click on "Subscribe"
$('#new-popup input.tnp-submit').click(function(event) {
var date = new Date();
date.setTime(date.getTime() + (30 * 24 * 60 * 60 * 1000));
expires = "; expires=" + date.toGMTString();
document.cookie = "testbb2020=subscribed" + expires + "; path=/"; {
}
});
});
JQuery no longer has an active plugin for this. Two alternatives exist depending on your needs:
you can use JS-Cookie for a way to work with cookies in Javascript
you can use LocalStorage instead of cookies
LocalStorage is the easier way, but if you need compatibility with older browsers go with cookies.
I am saving and restoring cookies using JavaScript in my website and I encountered an issue where I cannot delete those cookies.
I tries deleting then in code and also by clearing chrome history (from the beginning of time). I have red written posts and tried all sort of things but nothing fixed it for me.
here's my code that handles the cookies:
var createCookie = function (name, value, days) {
var expires;
if (days) {
var date = new Date();
date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
expires = "; expires=" + date.toGMTString();
}
else {
expires = "";
}
document.cookie = name + "=" + value + expires + "; path=/";
}
function getCookie(c_name) {
if (document.cookie.length > 0) {
c_start = document.cookie.indexOf(c_name + "=");
if (c_start != -1) {
c_start = c_start + c_name.length + 1;
c_end = document.cookie.indexOf(";", c_start);
if (c_end == -1) {
c_end = document.cookie.length;
}
return unescape(document.cookie.substring(c_start, c_end));
}
}
return "";
}
function deleteCookie(name) {
createCookie(name, "", -1);
}
after deleting chorme history, I execute this line of code :
var cookieHdrStr = getCookie("cart_header");
and I expectcookieHdrStr to be null/undefined but instead it restores the last cookie I saved.
I found what was wrong...
It turns out I had a line of code I wasn't aware of:
window.onbeforeunload = function () { saveDocumentCookie(); }
whenever unloading the page it was saving the cookies, so even when I deleted them and pressed f5 to refresh the page, before refreshing it was saving cookies.
Can red and blue outlined names be different. I have written the code below. Or if there is any better way.
set_custom_cookies: function ( cookieName,cookieData,days ) {
if ( days ) {
var date = new Date();
date.setTime( date.getTime()+( days*24*60*60*1000 ) );
//cookie expiration date
var expires = "; expires="+date.toGMTString();
} else var expires = "";
//add cookie info
document.cookie = cookieName + "=" +cookieData + expires + "; path=/";
}
When you pass data to the function set_custom_cookies() you send an argument cookieName. This is the name of the cookie that you want to change. Call this something else.
set_custom_cookies("myCustomName", cookieData, days);