Cookies on external server - javascript

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);}

Related

Unable to get block cookie value in Internet Explorer 11

Hi Anyone please help me:
var cookieBlockedUrl = ""<%URL%>"";
var cookieName = ""cmdTestCookie"";
xDeleteCookie(cookieName); // don't get false positive
document.cookie = cookieName + ""=test; path=/"";
var cookieString = document.cookie || """";
var cookies = cookieString.split(/\s*;\s*/);
var cookieFound = 0;
for (var i in cookies) {
var cookie = cookies[i];
var dough = cookie.split(/\s*=\s*/);
if (dough[0] == cookieName) {
cookieFound = 1; break;
}
}
xDeleteCookie(cookieName);
if (cookieFound != 1) {
window.location = cookieBlockedUrl
}
function xDeleteCookie(name) {
var oldDate = new Date(1970, 1, 1);
document.cookie = cookieName + ""=0; expires="" + oldDate.toGMTString();
}"
Above code is for redirecting to a specific page if the cookies are blocked from the browser the page is redirecting in every browser but not only in Internet Explorer 11

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.

How to set a cookie that prevents further javascript alerts?

I have this code for detecting android:
var mobile = (/android/i.test(navigator.userAgent.toLowerCase()));
if (mobile){
alert("Message to android users");
}
...but how do I get that script to also set a cookie so the android user doesn't continue getting the alert (either on reloading the page, returning later to the page, or navigating to other pages which have the alert)?
I also have this, which uses a cookie to avoid a user viewing a "welcome page" they've already seen:
var RedirectURL = "http://www.example.com/real-home-page.html";
var DaysToLive = "365";
var CookieName = "FirstVisit";
function Action() {
location.href = RedirectURL;
}
DaysToLive = parseInt(DaysToLive);
var Value = 'bypass page next time';
function GetCookie() {
var cookiecontent = '';
if(document.cookie.length > 0) {
var cookiename = CookieName + '=';
var cookiebegin = document.cookie.indexOf(cookiename);
var cookieend = 0;
if(cookiebegin > -1) {
cookiebegin += cookiename.length;
cookieend = document.cookie.indexOf(";",cookiebegin);
if(cookieend < cookiebegin) { cookieend = document.cookie.length; }
cookiecontent = document.cookie.substring(cookiebegin,cookieend);
}
}
if(cookiecontent.length > 0) { return true; }
return false;
}
function SetCookie() {
var exp = '';
if(DaysToLive > 0) {
var now = new Date();
then = now.getTime() + (DaysToLive * 24 * 60 * 60 * 1000);
now.setTime(then);
exp = '; expires=' + now.toGMTString();
}
document.cookie = CookieName + '=' + Value + exp;
return true;
}
if(GetCookie() == true) { Action(); }
SetCookie();
Can the second script be adapted and combined into the first to do something like:
function Action() {
don't-open-that-alert-again;
I've googled and found some js cookie scripts, but all over 100K. Prefer something as succinct as the above.

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