Cookies aren't available on new window on localhost - javascript

I'm using the following code to set a cookie
function setCookie(key, value) {
var expires = new Date();
expires.setTime(expires.getTime() + (1 * 24 * 60 * 60 * 1000));
document.cookie = key + '=' + value + ';expires=' + expires.toUTCString();
}
setCookie('test', '1');
The code is setting the cookie correctly (inspect element reveals the cookie has been set), however only on the page that the cookie is being set. I'm trying to open a new browser window and use that cookie value, however, it won't read the cookie.
I'm also on localhost on my local machine, so I believe that's where the error lies.
How can I fix it so that the cookie I set can be used across all pages on localhost?

this works for me
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=/";
}
setCookie('test', 'Bond007', 365);

Related

Script to change cookie expiration to 6 months

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')

Cookies work between HTTP pages, not HTTPS pages

I am trying to send cookies from one HTTPS page to another. My function which sets cookies from a HTML form runs on the submit button. However the cookies are not present in second page.
It all works in my HTTP test page.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript"></script>
$(document).ready(function() {
$('#formid').on("submit", function(e) {
e.preventDefault()
var form = $(this).serialize();
var d = new Date();
d.setTime(d.getTime() + (1 * 24 * 60 * 60 * 1000));
var expires = "expires=" + d.toUTCString();
console.log(form);
for (data_form of form) {
document.cookie = data_form + "=" + data_form.value + ";" + expires + ";path=/";
console.log(data_form.value)
}
});
});

Javascript if cookie exist apply css

I want to apply css through javascript if cookie xxxexist - code:
<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=/";
}
var kuki = document.cookie.indexOf('cookie_name=xxx');
alert(kuki);
if (kuki != -1)
{
document.getElementById("ads-back").style.display = "none";
document.getElementById("ffield").style.display = "none";
document.getElementById("bcd").style.display = "none";
}
else { setCookie(xxx, 1, 1) }
</script>
The problem is that I always receiving -1 it should after seting cookie setCookie(xxx, 1, 1) get different value?
setCookie(xxx, 1, 1)
As you are setting cookie name with xxx variable and finding it with cookie_name as below that is the issue..try to find the index of cookie actual name set then it will work.
var kuki = document.cookie.indexOf('cookie_name=xxx');
To save cookie you have to use following format
document.cookie = cname + "=" + cvalue + ";expires=" + expires + ";";
To get saved cookies you have to use following both ways because if you have saved more than one cookie your cookie may not be the first element of the cookie array so you have to check both 'cookie_name=xxx' and
' cookie_name=xxx'
var kuki1 = document.cookie.indexOf('cookie_name=xxx');
var kuki2 = document.cookie.indexOf(' cookie_name=xxx');

add a variable when setting a javascript cookie

I've been trying to add a variable when setting a cookie but no luck. The cookie is created but the value is not passed and it appears as +content+
function createCookie(name, value, expires, path, domain) {
var cookie = name + "=" + value + ";";
if (expires) {
// If it's a date
if(expires instanceof Date) {
// If it isn't a valid date
if (isNaN(expires.getTime()))
expires = new Date();
}
else
expires = new Date(new Date().getTime() + parseInt(expires) * 1000 * 60 * 60 * 24);
cookie += "expires=" + expires.toGMTString() + ";";
}
if (path)
cookie += "path=" + path + ";";
if (domain)
cookie += "domain=" + domain + ";";
document.cookie = cookie;
}
function updateCookie(){
var content = "value of cookie";
createCookie("newcookie", "+content+", new Date(new Date().getTime() + 10000));
}
I think you want
var content = "value of cookie";
createCookie("newcookie", content , new Date(new Date().getTime() + 10000));

Not able to set cookies secure and HttpOnly properties

For whatever reason when I try to set the secure and HttpOnly properties through Javascript, they fail to get set. Here is the code that is being used:
function Selected(StationID,QueryString)
{
ClearColours();
document.getElementById(StationID).className='StationSummary_Container_Selected';
setCookie('selectedItem',StationID,1);
setCookie('selectedItemValue',StationID,1);
setCookie('selectedItemQString',QueryString,1);
window.location="#" + StationID;
parent.frames["stationDetail"].location = "StationDetail.aspx?" + QueryString;
parent.frames["message"].location = "StationMessage.aspx?" + QueryString;
}
function setCookie(NameOfCookie, value, expiredays) {
var ExpireDate = new Date();
ExpireDate.setTime(ExpireDate.getTime() + (expiredays * 24 * 3600 * 1000));
var newCookie = NameOfCookie + "=" + escape(value) + ((expiredays == null) ? "" : "; expires=" + ExpireDate.toGMTString()) + "; Secure; HttpOnly";
document.cookie = newCookie;
}
Thanks in advance for any tips on this.
The browser does not allow you to read or write HttpOnly attribute using JavaScript for security reasons.
The clue is in the name, I guess: HttpOnly.
You can set these attributes on the server if you need to.

Categories

Resources