How long does it take to write to document.cookie - javascript

Was wondering how long it takes to write to document.cookie. Ran into an edge case when setting a cookie and re-directing to another page and the document.cookie was not getting set. Seemed to have different performance on a desktop (Chrome, firefox) vs iphone/tablet (safari)
Seemed to worked correctly in all cases when I added a set timeout of about 500ms
// writing cookie out
function set_cookie(name, value ) {
var date = new Date();
date.setTime(date.getTime() + (365 * 24 * 60 * 60 * 1000));
var cookie = name + "=" + value + "; expires=" + date.toGMTString() + ";";
document.cookie = cookie;
}
// reading cookie
function read_Cookie(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) {
var cVal = c.substring(nameEQ.length, c.length);
return cVal;
}
}
return null;
}
// button click setting cookie and navigation
$("#goToWebButton").click(function() {
if ($('#chkDontShow').attr('checked') == 'checked') {
set_cookie('IgnoreInAppLink','web');
}
setTimeout(function(){window.location.href = '';}, 500);
});
$("#goToAppButton").click(function() {
if ($('#chkDontShow').attr('checked') == 'checked') {
set_cookie('IgnoreInAppLink','app');
}
setTimeout(function(){window.location.href = '';},500);
});

JavaScript is by it's very nature single-threaded therefore the redirect shouldn't be executed until the cookie has been written regardless of how long it takes (almost instantaneous). That said, as pointed out at Is JavaScript guaranteed to be single-threaded? that may not always be the case. To mitigate this you might consider using jQuery's deferred object as such:
function set_cookie(name,value,deferred) { // added deferred argument
var date = new Date();
date.setTime(date.getTime() + (365 * 24 * 60 * 60 * 1000));
var cookie = name + "=" + value + "; expires=" + date.toGMTString() + ";";
document.cookie = cookie;
deferred.resolve();
}
var deferred = $.Deferred();
deferred.done(function() {
window.location.href = "";
});
$("#goToAppButton").click(function() {
if ($("#chkDontShow").attr("checked") == "checked") {
set_cookie("IgnoreInAppLink","web",deferred);
} else {
deferred.resolve();
}
}

Related

Website not getting cookie info correctly and spamming reload

I'm trying to define a version for my website so it can reload the resources if the versions don't match. The problem is that when I fetch the cookie, the cookie value is not returned. The result of this is that the website is in a constant state of reloading.
I made sure that the cookie was there and I tried using my functions in the console and setting the cookie manually.
Webpage:
var version = '1.0.0';
var cVersion = version == getCookie("version");
if(!cVersion) {
setCookie("version", version, 1000);
window.location.reload(true);
}
Cookies Script:
function setCookie(cname, cvalue, exdays) {
var d = new Date();
d.setTime(d.getTime() + (exdays * 24 * 60 * 60 * 1000));
var expires = "expires="+d.toUTCString();
document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/";
}
function getCookie(cname) {
var name = cname + "=";
var decodedCookie = decodeURIComponent(document.cookie);
var ca = decodedCookie.split(';');
for(var i = 0; i < ca.length; i++) {
var c = ca[i];
while (c.charAt(0) == ' ') {
c = c.substring(1);
}
if (c.indexOf(name) == 0) {
return c.substring(name.length, c.length);
}
}
return "";
}
The website should reload and update the version number if they are different and do nothing if they are the same.

Cookies disappear after setting them in Microsoft edge

I'm trying to set cookies that are permanent in Microsoft edge. They last only until I close the browser. Yes I have cookies enabled. Here is some code I found from a while ago:
var cookieHandler = {
setCookie : function(name, value, days, time)
{
var expires = "";
if(days)
{
var date = new Date();
date.setTime(date.getTime() + (time || (days * 24 * 60 * 60 * 1000)));
expires = "; expires=" + date.toUTCString();
}
document.cookie = name + "=" + (value || "") + expires + "; path=/";
},
getCookie : function(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;
},
eraseCookie : function(name)
{
document.cookie = name + '=; Max-Age=-99999999999;';
}
};
Yeah when I reopen the browser my cookies are gone. Does anyone have working code for cookies in Microsoft edge?
Edit:
I'm using the file:/// origin.

how can i test my script to delete cookies

I wrote a script in javascript to delete all cookies (except some included in a whitelist) within the current domain (using document.cookie). How can I make sure that it is working and indeed deleting the cookies?
I ran it in the browser by including it in an html file and then opening that file, but I don't understand how to test that it will delete cookies within the domain since when I open an html file it is not associated with a domain.
Here is my code:
//cookies we need
const whitelist = [
'example_cookie',
];
function removeUnnecessaryCookies() {
let decodedCookie = decodeURIComponent(document.cookie); //check for special characters
let allCookies = decodedCookie.split(';'); //make array of all cookies in domain
for (var i = 0; i < allCookies.length; i++) {
let cookie = allCookies[i];
if (!whitelist.includes(cookie)) {
deleteCookie(cookie);
}
}
}
/* helper function to delete cookies */
function setCookie(cookieName, cookieValue, cookieExpiry) {
let date = new Date();
date.setTime(date.getTime() + (cookieExpiry*24*60*60*1000));
let expires = "expires=" + date.toUTCString();
document.cookie = cookieName + "=" + cookieValue + ";" + expires + ";path=/";
}
function deleteCookie(cookieName) {
setCookie(cookieName, '', -100);
}
removeUnnecessaryCookies();
Write a getCookie method and test for that. Here is an example:
function setCookie(name, value, days) {
var expiry = new Date()
expiry.setTime(expiry.getTime() + (days * 24 * 60 * 60 * 1000))
var expires = 'expires=' + expiry.toUTCString()
document.cookie = name + '=' + value + ';' + expires + ';' + 'path=/'
}
function getCookie(name) {
var name = name + '='
var decodedCookie = decodeURIComponent(document.cookie)
var ca = decodedCookie.split(';')
for(var i = 0; i < ca.length; i++) {
var c = ca[i]
while (c.charAt(0) == ' ') {
c = c.substring(1)
}
if (c.indexOf(name) == 0) return c.substring(name.length, c.length)
}
return false
}
// set cookie
setCookie('mycookie', '1', 365);
// get cookie
getCookie('mycookie');
getCookie('joe'); // returns false
Your best bet would be to spin up a localhost webserver (something like WAMP or MAMP or Mac should do the trick) and drop a cookie. Look at the domain in your browser and copy that.

Cookies cannot read in wordpress

I created javascript cookie. But i can't read that cookie in wordpress. setcookie() function also not working. Only $_COOKIE is working .But it expiring in one minute.
You can use following javascript function to create, read and delete cookies
CREATE COOKIE
`
function createCookie(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 = encodeURIComponent(name) + "=" + encodeURIComponent(value) + expires + "; path=/";
}
`
READ COOKIE
`
function readCookie(name) {
var nameEQ = encodeURIComponent(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 decodeURIComponent(c.substring(nameEQ.length, c.length));
}
return null;
}
`
DELETE COOKIE
`
function eraseCookie(name) {
createCookie(name, "", -1);
}
`
Now, call javascript functions as:
createCookie('test','hello','5');
readCookie('test');
eraseCookie('test');

How to conver these exact create/read cookie functions to localstorage?

I want to replace my current functions of creating and reading cookie, and save it into the local storage instead.
How can I replicate this for local storage instead?
function createCookie(name, value, days) {
var c_date,
c_name = name + "=" + value + ";",
c_expi = "",
c_domain = "domain=.domain.com;",
c_path = "path=/";
if (days > 0) {
c_date = new Date();
c_date.setTime(c_date.getTime() + (days * 24 * 60 * 60 * 1000));
c_expi = "expires=" + c_date.toGMTString() + ";";
}
// create the cookie
document.cookie = c_name + c_expi + c_domain + c_path;
}
function readCookie(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;
}
Using a LocalStorage is to easy then store a cookie value .. you need to just write
// Store
localStorage.setItem("lastname", "Smith"); // here is lastname is your key
// Retrieve
document.getElementById("result").innerHTML = localStorage.getItem("lastname");
If you want to check that Browser support local
Storage then .
if(typeof(Storage) !== "undefined") {
// Code for localStorage/sessionStorage.
} else {
// Sorry! No Web Storage support..
}
but before use localStoreage you must read
HTML 5 Storage's same origin policy
you can also store javascript object as JSON
function createCookie(name, value, days) {
var c = {
domain = ".domain.com",
path = "path=/"
}
c[name] = value;
if (days > 0) {
var date = new Date();
date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
c.expi = date.toGMTString();
}
//local storaage
localStorage.setItem('somename', JSON.stringify(c));
}
function readCookie(name) {
var c = JSON.parse(localStorage.getItem('somename') || '{}');
return c[name];
}

Categories

Resources