How to set cookie for a day - javascript

This is the code I'm using. Please help me to set cookie for a day! I want to show welcome page when a visitor come back after 24 hours.
<SCRIPT LANGUAGE="JavaScript">
<!-- hide from old browsers
function setCookie(name, value, expires, path, domain, secure) {
document.cookie = name + "=" + escape(value) +
((expires) ? "; expires=" + expires.toGMTString() : "") +
((path) ? "; path=" + path : "") +
((domain) ? "; domain=" + domain : "") +
((secure) ? "; secure" : "");
}
function setsplash() {
setCookie("splash", "1", "", "/");
}
//-->
</SCRIPT>

Your method setCookie() is defined as
function setCookie(name, value, expires, path, domain, secure)
The third parameter is the expiration time. But you're calling
setCookie("splash", "1", "", "/");
i.e. the expires parameter is "". If you want the cookie to expire after 24 hours, use something like this instead:
var expires = (new Date(Date.now() + 86400000)).toUTCString(); // 86400000 milliseconds is 24 hours
setCookie("splash", "1", expires, "/");

Related

Unable to set SameSite attribute on cookie using JavaScript in an iFrame

I have an issue setting a cookie with SameSite=none using JavaScript.
I have a client's site which pulls in content from our site into an iFrame. I need to be able to set a cookie on the user (of the client's site)'s machine which will remember a layout preference the next time the user visits the iFrame.
I have the following code which works fine in non-Chrome browsers:
function setCookie(c_name, value, exdays) {
var exdate = new Date();
exdate.setDate(exdate.getDate() + exdays);
var c_value = escape(value) + ((exdays == null) ? "" : "; expires=" + exdate.toUTCString());
document.cookie = c_name + "=" + c_value;
}
However, if I add in a line (highlighted below) to add the SameSite and Secure attributes, the cookie is not set (in any browser):
function setCookie(c_name, value, exdays) {
var exdate = new Date();
exdate.setDate(exdate.getDate() + exdays);
var c_value = escape(value) + ((exdays == null) ? "" : "; expires=" + exdate.toUTCString());
**if (c_name == "preferenceCookie") { c_value += ";SameSite=None;Secure" };**
document.cookie = c_name + "=" + c_value;
}
I'm sure I'm missing something stupendously obvious, but this is driving me mad. (Or can it just not be done?)
(Oh - and it's my first post - please be gentle!)
Thanks.

Javascript - Delete Cookie by the beginning of the name [duplicate]

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) {
createCookie(cookie_name,"",-1);
}
Try this:
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:
function get_cookie(name){
return document.cookie.split(';').some(c => {
return c.trim().startsWith(name + '=');
});
}
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) {
document.cookie = name+'=; Max-Age=-99999999;';
}
would this work?
function eraseCookie(name) {
document.cookie = name + '=; Max-Age=0'
}
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.
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.
Here is an implementation of a delete cookie function with unicode support from Mozilla:
function removeItem(sKey, sPath, sDomain) {
document.cookie = encodeURIComponent(sKey) +
"=; expires=Thu, 01 Jan 1970 00:00:00 GMT" +
(sDomain ? "; domain=" + sDomain : "") +
(sPath ? "; path=" + sPath : "");
}
removeItem("cookieName");
If you use AngularJs, try $cookies.remove (underneath it uses a similar approach):
$cookies.remove('cookieName');
You can do this by setting the date of expiry to yesterday.
Setting it to "-1" doesn't work. That marks a cookie as a Sessioncookie.
To delete a cookie I set it again with an empty value and expiring in 1 second.
In details, I always use one of the following flavours (I tend to prefer the second one):
1.
function setCookie(key, value, expireDays, expireHours, expireMinutes, expireSeconds) {
var expireDate = new Date();
if (expireDays) {
expireDate.setDate(expireDate.getDate() + expireDays);
}
if (expireHours) {
expireDate.setHours(expireDate.getHours() + expireHours);
}
if (expireMinutes) {
expireDate.setMinutes(expireDate.getMinutes() + expireMinutes);
}
if (expireSeconds) {
expireDate.setSeconds(expireDate.getSeconds() + expireSeconds);
}
document.cookie = key +"="+ escape(value) +
";domain="+ window.location.hostname +
";path=/"+
";expires="+expireDate.toUTCString();
}
function deleteCookie(name) {
setCookie(name, "", null , null , null, 1);
}
Usage:
setCookie("reminder", "buyCoffee", null, null, 20);
deleteCookie("reminder");
2
function setCookie(params) {
var name = params.name,
value = params.value,
expireDays = params.days,
expireHours = params.hours,
expireMinutes = params.minutes,
expireSeconds = params.seconds;
var expireDate = new Date();
if (expireDays) {
expireDate.setDate(expireDate.getDate() + expireDays);
}
if (expireHours) {
expireDate.setHours(expireDate.getHours() + expireHours);
}
if (expireMinutes) {
expireDate.setMinutes(expireDate.getMinutes() + expireMinutes);
}
if (expireSeconds) {
expireDate.setSeconds(expireDate.getSeconds() + expireSeconds);
}
document.cookie = name +"="+ escape(value) +
";domain="+ window.location.hostname +
";path=/"+
";expires="+expireDate.toUTCString();
}
function deleteCookie(name) {
setCookie({name: name, value: "", seconds: 1});
}
Usage:
setCookie({name: "reminder", value: "buyCoffee", minutes: 20});
deleteCookie("reminder");
For people who just want 1 line of code to delete a cookie:
If you created a cookie, for example in a web browser console with document.cookie = "test=hello"
You can delete it with:
document.cookie = "test=;expires=" + new Date(0).toUTCString()
Or if you prefer to write the UTC date directly:
document.cookie = "test=;expires=Thu, 01 Jan 1970 00:00:00 GMT"
If you are on a different path than the cookie (for example if you want to delete a cookie that is used on all paths), you can add path=/; after test=; and if you are on a different domain (for example when a cookie is set for all subdomains by using .example.com instead of www.example.com), you can add domain=.example.com; after test=;.
Update: instead of expires=..., using Max-Age=0 like in other answers works also (tested with Firefox).
I had trouble deleting a cookie made via JavaScript and after I added the host it worked (scroll the code below to the right to see the location.host). After clearing the cookies on a domain try the following to see the results:
if (document.cookie.length==0)
{
document.cookie = 'name=example; expires='+new Date((new Date()).valueOf()+1000*60*60*24*15)+'; path=/; domain='+location.host;
if (document.cookie.length==0) {alert('Cookies disabled');}
else
{
document.cookie = 'name=example; expires=Thu, 01 Jan 1970 00:00:00 GMT; path=/; domain='+location.host;
if (document.cookie.length==0) {alert('Created AND deleted cookie successfully.');}
else {alert('document.cookies.length = '+document.cookies.length);}
}
}
I use this on my websites that works on Chrome and Firefox.
function delete_cookie(name) { document.cookie = name +'=; Path=/; Domain=' + location.host + '; Expires=Thu, 01 Jan 1970 00:00:01 GMT; SameSite=None; Secure' }
if ("JSESSIONID".equals(cookie.getName()) || "LtpaToken2".equals(cookie.getName())) {
cookie.setValue("");
cookie.setPath("/");
cookie.setMaxAge(0);
cookie.setHttpOnly(true);
response.addCookie(cookie);
}
I used to generate the cookie from backend and redirect to frontend. The only way I got it working has been to set the expires date in the past in the backned and redirect back on frontend
We don't have the ability to delete cookies in JavaScript, so to delete it we need to create another cookie with an earlier date.
Set Cookie
let expires = null
const cookieName = 'userlogin'
const d = new Date();
d.setTime(d.getTime() + 2 * 24 * 60 * 60 * 1000);
document.cookie = cookieName + "=" + value+ ";" + expires + ";path=/";
Delete Cookie
let expires = null
const d = new Date();
d.setTime(d.getTime() - 2 * 24 * 60 * 60 * 1000);
expires = "expires=" + d.toUTCString();
document.cookie = 'userlogin' + "=" + value+ ";" + expires + ";path=/";

Cookie JavaScript Html

I want to change cookie from the marked 'object' in JS.
Can you help me?? Thanks
My code JS:
function tryCookies(src, domain) {
if (src == "t:s") {
setCookie("$dtype", "", -1, domain);
setCookie("$dtype", src, 1, domain);
}
};
function setCookie(name, value, days, domain) {
var date = new Date();
date.setDate(date.getDate() + days);
document.cookie = name + "=" + escape(value) + ";expires=" + date.toGMTString() + ";domain=" + domain + ";path=/";
};
My code HTML:
<object class="cd" data="WebSite" type="text/html" onload="tryCookies('t:s', 'cdiscount.com.co');"></object>

Is there a way I can have Javascript tell me why a cookie wasn't set?

Here is my code for setting a cookie:
function setCookie(c_name, value, expiredays)
{
alert("setting cookie!");
var exdate = new Date();
exdate.setDate(exdate.getDate() + expiredays);
document.cookie = c_name + "=" + escape(value) +
((expiredays === null) ? "" : ";expires=" + exdate.toUTCString());
}
I'm using Phonegap to make an app on Android phones, which should just use and set cookies like a regular browser. It doesn't seem to be setting the cookie, though, and because of the environment (on my pnone), I can't debug.
So, is there a way I can make an alert to tell me if document.cookie fails, and ideally any error message that might tell me why?
I tried just doing alert(document.cookie), but it's not outputting anything, so I'm hoping there's another way to trap the output.
You can use try/catch statement:
function setCookie(c_name, value, expiredays)
{
try {
alert("setting cookie!");
var exdate = new Date();
exdate.setDate(exdate.getDate() + expiredays);
document.cookie = c_name + "=" + escape(value) +
((expiredays === null) ? "" : ";expires=" + exdate.toUTCString());
} catch(error) {
// deal with errors
alert(error);
}
}

redirection cookie stuck in loop

For some reason this script gets stuck in a redirection loop and wont let you leave "android.html". The url bar shows it is trying to go to "index.html" but it just flashes then stays on "android.html"
var caution = false
function setCookie(name, value, expires, path, domain, secure) {
var curCookie = name + "=" + escape(value) +
((expires) ? "; expires=" + expires.toGMTString() : "") +
((path) ? "; path=" + path : "") +
((domain) ? "; domain=" + domain : "") +
((secure) ? "; secure" : "")
if (!caution || (name + "=" + escape(value)).length <= 4000)
document.cookie = curCookie
else
if (confirm("Cookie exceeds 4KB and will be cut!"))
document.cookie = curCookie
}
function getCookie(name) {
var prefix = name + "="
var cookieStartIndex = document.cookie.indexOf(prefix)
if (cookieStartIndex == -1)
return null
var cookieEndIndex = document.cookie.indexOf(";", cookieStartIndex + prefix.length)
if (cookieEndIndex == -1)
cookieEndIndex = document.cookie.length
return unescape(document.cookie.substring(cookieStartIndex + prefix.length, cookieEndIndex))
}
function deleteCookie(name, path, domain) {
if (getCookie(name)) {
document.cookie = name + "=" +
((path) ? "; path=" + path : "") +
((domain) ? "; domain=" + domain : "") +
"; expires=Thu, 01-Jan-70 00:00:01 GMT"
}
}
function fixDate(date) {
var base = new Date(0)
var skew = base.getTime()
if (skew > 0)
date.setTime(date.getTime() - skew)
}
var now = new Date()
fixDate(now)
now.setTime(now.getTime() + 365 * 24 * 60 * 60 * 1000)
var visits = getCookie("indexVisited")
if (!visits)
window.location.replace("./android.html");
else
window.location.replace("./index.html");
setCookie("indexVisited", visits, now)
Besides missing a whole lot of semicolons, your code tries to set the cookie after it redirects to another page. Javascript stops executing upon a redirect, so your setCookie call never gets executed. Try moving it up before the redirects.

Categories