How to set Javascript cookie in all the pages / globally? - javascript

I'm having a huge problem with my code, I am trying to check if a cookie exists, and if it does exist, i dont want it to do anything.
Its working fine on page1, but when i navigate to page2 it overrides the cookie, instead of doing nothing (the pages is from the same website)
Heres my script
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;
}
function getCookie(c_name) {
var i, x, y, ARRcookies = document.cookie.split(";");
for (i = 0; i < ARRcookies.length; i++) {
x = ARRcookies[i].substr(0, ARRcookies[i].indexOf("="));
y = ARRcookies[i].substr(ARRcookies[i].indexOf("=") + 1);
x = x.replace(/^\s+|\s+$/g,"");
if (x == c_name) {
return unescape(y);
}
}
}
var omgpost = getCookie("omgpost");
if (omgpost == null || omgpost == "") {
setCookie("omgpost", "1", 1);
} else {
alert('cookie installed already');
}
This is working fine, when I don't have the cookie installed and entering this site, I'm adding the cookie, and I'm getting the confirmation message each time I refresh the page1.
But when navigating to page2 its recreating the cookie??? I don't want that! I want the cookie to be there, and can't be changed, only when it has expired, how can I do that?

Set Cookie Path using path=/
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())
+ "; path=/";
document.cookie=c_name + "=" + c_value;
}

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.

Cookie in html webview android

Hi I need to know is how to read cookies on a html web-view . I have a banner to close it generates a cookie and the idea would be to go to another page that has the banner he would read the cookie to see if the User already have clicked ...
this is the cookie code
function createCookie() {
var d = new Date();
d.setTime(d.getTime() + (1*24*60*60*1000));
var expires = "expires="+d.toUTCString();
document.cookie = "cookie=cookie ; " + expires+';path = http://www.pitstop.com.br/';
document.getElementById('banner_id').style.display='none';
}
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 null;
}
function banner_cookie(){
var teste = getCookie('cookie');
if(teste !=null){
alert(teste);
document.getElementById('banner_id').style.display='none';
}else{
document.getElementById('banner_id').style.display
}
}
You have many issues that seems to stem from wishful thinking and misunderstanding.
For example your path is wrong and you need to pass a name to the cookie script instead of hardcoding the name "cookie"
You need to take a well tested cookie script and use it properly.
function getCookie(name) {
var start = document.cookie.indexOf(name + "=");
var len = start + name.length + 1;
if ((!start) && (name != document.cookie.substring(0, name.length))) {
return null;
}
if (start == -1) return null;
var end = document.cookie.indexOf(';', len);
if (end == -1) end = document.cookie.length;
return unescape(document.cookie.substring(len, end));
}
function setCookie(name, value, expires, path, domain, secure) {
var today = new Date();
today.setTime(today.getTime());
if (expires) {
expires = expires * 1000 * 60 * 60 * 24;
}
var expires_date = new Date(today.getTime() + (expires));
document.cookie = name + '=' + escape(value) +
((expires) ? ';expires=' + expires_date.toGMTString() : '') + //expires.toGMTString()
((path) ? ';path=' + path : '') +
((domain) ? ';domain=' + domain : '') +
((secure) ? ';secure' : '');
}
function deleteCookie(name, path, domain) {
if (getCookie(name)) document.cookie = name + '=' +
((path) ? ';path=' + path : '') +
((domain) ? ';domain=' + domain : '') +
';expires=Thu, 01-Jan-1970 00:00:01 GMT';
}
Your script:
function banner_cookie(){
var teste = getCookie('showbanner')=="true";
document.getElementById('banner_id').style.display=teste?"block":"none";
}
and to set:
setCookie("showbanner","true",14,"/"); // 2 weeks accessible to all website
and to remove
deleteCookie("showbanner","/");

Javascript function to execute only once

I have been working on a script to show an alert box only once (using cookies). Here is what I have so far:
<script type="text/javascript">
function cookie(){
var x = document.cookie;
if (x = "") {
alert("Welcome to Steampunk Inc!");
document.cookie = 'iwashere=iwashere; expires=Fri, 31-Dec-9999 23:59:59 GMT;';
} else if (x = "iwashere=iwashere") {
console.log("You came back!");
}
}
cookie();
</script>
I have this as the first thing in the body of my html file. The code is on the index page on my website here.
The main problem is that you are using = operator with if. = operator assigns value to the variable. Instead you should use == operator to compare.
In addition document.cookie will return all cookies you have stored for your site. You should use some functions to get / set the specific cookies
Here is sample code:
<script type="text/javascript">
function getCookie(name) {
var value = "; " + document.cookie;
var parts = value.split("; " + name + "=");
if (parts.length == 2) return parts.pop().split(";").shift();
}
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;
}
function cookie(){
var x = getCookie("iwashere");
if (x == "" || x == null) {
alert("Welcome to Steampunk Inc!");
setCookie("iwashere", "iwashere", 365);
} else if (x == "iwashere") {
console.log("You came back!");
}
}
cookie();
</script>

Cookie is not working and returning undefined

I'm using the following code for my set and get Cookie:
$.setCookie = function (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;
};
$.getCookie = function (c_name) {
var i, x, y, ARRcookies = document.cookie.split(";");
for (i = 0; i < ARRcookies.length; i++) {
x = ARRcookies[i].substr(0, ARRcookies[i].indexOf("="));
y = ARRcookies[i].substr(ARRcookies[i].indexOf("=") + 1);
x = x.replace(/^\s+|\s+$/g, "");
if (x == c_name) {
return unescape(y);
}
}
};
Then I simply created two test click functions for 2 buttons:
$('#quick-true').click(function(){
$.setCookie('quick-status', true, 365);
var get = $.getCookie('quick-status');
alert('Status: '+get);
});
$('#quick-false').click(function(){
$.setCookie('quick-status', false, 365);
var get = $.getCookie('quick-status');
alert('Status: '+get)
});
But when clicking either #quick-true or #quick-false the alert says Status: undefined
Can anyone help me why this is happening. I know quite a bit about Cookies and I worked with them a lot but this time im lost.
Your code looks fine to me, but to be sure I created a test HERE, and it's working as expected for me.
There's probably something other than the code you have posted that is causing the problem, exactly what is hard to tell.

Use JavaScript to change background image of a div in another page

I'm using the following line to change background of the div Wrapper to an image:
$("#wrapper").css("background","url(images/bg.jpg) no-repeat 0 0");
However, Wrapper exists in another page from the function where I am calling this line of code , so when I navigate to the page with Wrapper in it, it has not changed.
Is there anyway I am able to change the background of Wrapper from another page?
Thanks
You could store the values in a cookie, working example here -> http://jsfiddle.net/manseuk/cEpjc/ :
store it in a cookie on the page you want to set the background :
setCookie('background','url(images/bg.jpg) no-repeat 0 0');
then on the "other" page do this :
$('#div').css('background',getCookie('background'));
For cookie reading and writing you could either use a jQuery plugin (thanks #Filip) or basic JavaScript cookie methods :
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;
}
function getCookie(c_name) {
var i, x, y, ARRcookies = document.cookie.split(";");
for (i = 0; i < ARRcookies.length; i++) {
x = ARRcookies[i].substr(0, ARRcookies[i].indexOf("="));
y = ARRcookies[i].substr(ARRcookies[i].indexOf("=") + 1);
x = x.replace(/^\s+|\s+$/g, "");
if (x == c_name) {
return unescape(y);
}
}
}

Categories