Document.cookie configure CookieJar for domain localhost - javascript

I am using a getCookie function to access cookies in a Pinia store. When trying to test this with Vitest, I get the following error:
Error: Cookie has domain set to the public suffix "localhost" which is a special use domain. To allow this, configure your CookieJar with {allowSpecialUseDomain:true, rejectPublicSuffixes: false}.
Below is the code for the getCookie function I am using:
//https://stackoverflow.com/a/5968306/14131782
function getCookie(name: string) {
var dc = document.cookie;
var prefix = name + "=";
var begin = dc.indexOf("; " + prefix);
var end = 0;
if (begin == -1) {
begin = dc.indexOf(prefix);
if (begin != 0) return null;
} else {
begin += 2;
end = document.cookie.indexOf(";", begin);
if (end == -1) {
end = dc.length;
}
}
return decodeURI(dc.substring(begin + prefix.length, end));
}
Is there some way I can configure document.cookie for testing this?

This was resolved by updating the tough-cookie module

Related

Delete specific cookie with Javascript

I need to delete a specific cookie from a website. At first I have tried several ways to delete ALL cookies, however none of them worked properly (not all cookies were deleted).
I also tried the below code to find the cookie I need to delete, but I can't figure out how to delete it after found it.
Can anyone help?
function getCookie(name) {
var dc = document.cookie;
var prefix = name + "=";
var begin = dc.indexOf("; " + prefix);
if (begin == -1) {
begin = dc.indexOf(prefix);
if (begin != 0) return null;
}
else
{
begin += 2;
var end = document.cookie.indexOf(";", begin);
if (end == -1) {
end = dc.length;
}
}
return decodeURI(dc.substring(begin + prefix.length, end));
}
function deleteCookie() {
var myCookie = getCookie("dropin_date");
if (myCookie == null) {
}
else {
// if cookie exists delete it
}
}
deleteCookie();
check this out.
function accessCookie(cookieName) {
var name = cookieName + "=";
var allCookieArray = document.cookie.split(';');
for(var i=0; i<allCookieArray.length; i++)
{
var temp = allCookieArray[i].trim();
if (temp.indexOf(name)==0)
return temp.substring(name.length,temp.length);
}
return "";
}
var delete_cookie = function(name) {
document.cookie = name + '=;expires=Thu, 01 Jan 1970 00:00:01 GMT;';
};
var mycookie = accesCookie('test');
if(mycookie != ''){
delete_cookie('test');
}
In order to delete a cookie set the expires date in the past. it will delete automatically

Cookies on external server

I'm using the code below to handle cookies, it works fine locally, but when I upload it to our testserver the cookies are not set (it's the same for Firefox, IE and Chrome, so I don't think it's a browser issue).
Cookies are allowed since I can set cookies using PHP setcookie("RFT_reeftWpLang", $lang, time()+29030400, dirname($_SERVER["SCRIPT_NAME"]), $_SERVER["SERVER_NAME"]);
Neither locally nor on the server I get any errors when I try to set document.cookie, but on the server console.log( getFilterCookie(cname)); return an empty string where I do get the expected value locally.
I know you probably can not say what's wrong without access to the server, but I hope you might tell me what to look for in order to pinpoint the error
function setFilterCookie(cname,cvalue,exdays) {
var cookiePath = "/";
var pathArray = window.location.pathname.split( '/' );
if (pathArray.length > 2 && $.trim(pathArray[1]) != "" ) {
cookiePath = cookiePath+pathArray[1];
}
var d = new Date();
d.setTime(d.getTime()+(exdays*24*60*60*1000));
var expires = "expires="+d.toGMTString();
try {
document.cookie = cname+"="+cvalue+"; "+expires+"; domain="+window.location.host+"; path="+cookiePath ;
} catch (e) {console.log(e);}
if(exdays < 0) {
document.cookie = cname+"="+cvalue+"; "+expires;
}
console.log( getFilterCookie(cname));
}
function getFilterCookie(cname) {
var name = cname + "=";
var ca = document.cookie.split(';');
for(var i=0; i<ca.length; i++) {
var c = $.trim(ca[i]);
if (c.indexOf(name)==0) {
return c.substring(name.length,c.length);
}
}
return "";
}
function delFilterCookie(cname) {
setFilterCookie(cname, "", -1);
}
Thank for helping
On our testserver we have the port in the url, so it get's part of the domain, it works's after I have changed my code to
var domainArray = window.location.host.split( ':' );
var domain = domainArray[0];
try {
console.log(document.cookie = cname+"="+cvalue+"; "+expires+"; domain="+domain+"; path="+cookiePath);
} catch (e) {
console.log(e);
console.log("fail setFilterCookie" + cname + " - " + cvalue + " - " + exdays);}

JavaScript Compiler Error in Tag Manager

I'm trying to use a cookie to set user pageviews per session through GTM. I'm using a custom JavaScript variable:
function readCookie(name) {
var cookieName = name + "=";
var cookieSplit = document.cookie.split(';');
for (var i = 0; i < cookieSplit.length; i++) {
var cookies = cookieSplit[i];
while (cookies.charAt(0) === ' ') cookies = cookies.substring(1, cookies.length);
if (cookies.indexOf(cookieName) === 0) return cookies.substring(cookieName.length, cookies.length);
}
return null;
}
function viewAppend() {
var oldCookie = readCookie('viewCount');
if (oldCookie === null) {
document.cookie = "viewCount=1; path=/";
} else {
var views = oldCookie + 1;
document.cookie = "viewCount="+views+"; path=/";
}
}
viewAppend();
I keep getting the same Compiler error: "Error at line 12, character 1: Parse error. ')' expected."
I can't seem to figure out what I'm doing wrong, but any help is appreciated.
------ EDIT ------
Via my comment below, this is my current code. Current error is : "Error at line 16, character 40: Parse error. Semi-colon expected"
function doStuff() {
function readCookie(name) {
var cookieName = name + "=";
var cookieSplit = document.cookie.split(';');
for(var i=0;i < cookieSplit.length;i++) {
var cookies = cookieSplit[i];
while (cookies.charAt(0) === ' ') cookies = cookies.substring(1,cookies.length);
if (cookies.indexOf(cookieName) === 0) return cookies.substring(cookieName.length,cookies.length);
}
return null;
}
function viewAppend() {
var oldCookie = readCookie('viewCount');
if (oldCookie === null) {
document.cookie = "viewCount="1"; path=/";
} else {
var views = parseInt(oldCookie) + 1;
document.cookie = "viewCount="+views+"; path=/";
}
}
}
You have quoting problems on this line:
document.cookie = "viewCount="1"; path=/";
it should be:
document.cookie = "viewCount=1; path=/";
You don't need to put quotes around the value of a cookie (and if you did, you could either escape them or use single quotes around the whole string).
Alright, I went back to the drawing board and tried approaching the problem another way. At first I was trying to build everything into a single custom JavaScript variable in GTM. That was folly. I decided to approach it as such:
First, I built a custom HTML tag in GTM to read/write the PageView cookie that fired on all pages.
<script>
function readCookie(name) {
var cookieName = name + "=";
var cookieSplit = document.cookie.split(';');
for(var i=0;i < cookieSplit.length;i++) {
var cookies = cookieSplit[i];
while (cookies.charAt(0) === ' ') cookies = cookies.substring(1,cookies.length);
if (cookies.indexOf(cookieName) === 0) return cookies.substring(cookieName.length,cookies.length);
}
return null;
}
function viewAppend() {
var oldCookie = readCookie('viewCount');
if (oldCookie === null) {
document.cookie = "viewCount=1; path=/";
} else {
var views = parseInt(oldCookie) + 1;
document.cookie = "viewCount="+views+"; path=/";
}
}
viewAppend();
</script>
Then I built a custom Javascript variable that read the cookie and returned it as an integer.
function doStuff() {
function readCookie(name) {
var cookieName = name + "=";
var cookieSplit = document.cookie.split(';');
for(var i=0;i < cookieSplit.length;i++) {
var cookies = cookieSplit[i];
while (cookies.charAt(0) === ' ') cookies = cookies.substring(1,cookies.length);
if (cookies.indexOf(cookieName) === 0) return cookies.substring(cookieName.length,cookies.length);
}
return null;
}
var oldCookie = readCookie('viewCount');
var views = parseInt(oldCookie);
return views;
}
Then I simply built my pagievew tag that triggered whenever the pageviews variable was greater than 4 on Window Load to indicate an engaged user.
Thanks #Barmar for the help thinking about the problem. Your questions definitely challenged how I was approaching it.

cookies set by javascript not retrievable

I have this script in JS
function setCookie(name, value, days) {
var d = new Date;
d.setTime(d.getTime() + 24*60*60*1000*days);
document.cookie = name + "=" + value + ";path=/;expires=" + d.toGMTString();
}
I can see in my Chrome browser options->settings that the cookie name "workLocation" is set. The domain for the cookie is "/", 'send for' option is "Any kind of Connection" and 'accessible to script' option is "Yes".
when I call the cookie using JS code below, it returns null.
function getCookie(name) {
var v = document.cookie.match('(^|;) ?' + name + '=([^;]*)(;|$)');
return v ? v[2] : null;
}
alert(getCookie("workLocation"));
I had tried using PHP to show cookies var_dump($_COOKIE); but it only shows codeigniter cookies "ci_session" and "httpUser". I had used the same javascript to set and get cookies and it's working, except for this page. Any ideas how to solve it?
cookie in server and in client is different the cookie in server is stored in
Local Storage
and the cookie in client is stored in
Cookies
if you want to get the cookie from js u can use this functions :
function getCookie(cname) {
var name = cname + "=";
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);
}
if (c.indexOf(name) == 0) {
return c.substring(name.length, c.length);
}
}
return "";
}
function checkCookie() {
var user = getCookie("username");
if (user != "") {
alert("Welcome again " + user);
} else {
user = prompt("Please enter your name:", "");
if (user != "" && user != null) {
setCookie("username", user, 365);
}
}
}
but if you want to get the cookie from php especially those session in CI
u can use this command $this->session->userdata("key");

Cookie only working without the www in front of my domain

I am setting a cookie in a disclaimer php file like this...
<script language = "JavaScript">
<!-- Begin hiding
function getCookieExpireDate(noDays){
var today = new Date()
var expr = new Date(today.getTime()+noDays*24*60*60*1000*365)
return expr.toGMTString()
}
function makeCookie(name, data, noDays){
var cookieStr = name + "="+ data
if (makeCookie.arguments.length > 2){
cookieStr += "; expires=" + getCookieExpireDate(noDays)
}
document.cookie = cookieStr
var hello="agreedterms.html";
window.location=hello;
}
function noway(){
var goodbye="index.html";
window.location=goodbye;
}
// End hiding -->
</script>
And then checking for it in index php like this....
<script language = "JavaScript">
function getCookieVal (offset) {
var endstr = document.cookie.indexOf (";", offset);
if (endstr == -1) {
endstr = document.cookie.length;
}
return unescape(document.cookie.substring(offset, endstr));
}
function getCookie (cookieName) {
var arg = cookieName + "=";
var argLength = arg.length;
var cookieLength = document.cookie.length;
var i = 0;
while (i < cookieLength) {
var j = i + argLength;
if (document.cookie.substring(i, j) == arg) {
return getCookieVal(j)
}
if (i == 0) {
break
}
}
return null;
}
if(getCookie('disclaimer') == null) {
location.href="disclaimer.php"
}
</script>
This all works fine if I access the site using mydomain.com - but if I use www.mydomain.com then it doesn't work.
Any ideas what I am doing wrong? Do I need to include the www somehow?
If I remeber you have to set the domain and path for the cookie by appending following to your cookie string
;domain=.domain.com;path=/
Where obviously you replace the domain by your domain. The . in front of the domain name makes it valid for all subdomains following the domain you are currently on.
Edit:
See also the following Stack Overflow answer: Creating a javascript cookie on a domain and reading it across sub domains

Categories

Resources