I am trying to find out if its the users first time on my webpage. I am currently storing a variable in local storage and checking if its null or not but it doesn't seem to work in Internet Explorer. What other method can I use to accomplish this?
var str_count = localStorage.getItem("count");
if (str_count == null || str_count == "null")
{
// Do something
}
Setting cookie with long expiration date is definitely more reliable that using localStorage as it is not yet supported by older browsers.
Check this code:
function createCookie(name,value,days) {
if (days) {
var date = new Date();
date.setTime(date.getTime()+(days*24*60*60*1000));
var expires = "; expires="+date.toGMTString();
}
else var expires = "";
document.cookie = name+"="+value+expires+"; path=/";
}
function readCookie(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) {
createCookie(name,"",-1);
}
Read more about cookies here.
You can set a cookie with
document.cookie = name + "=" + value + "; expires=" + exp + "; path=/";
More info here: http://www.w3schools.com/js/js_cookies.asp
More info here: http://www.quirksmode.org/js/cookies.html
As #Greg said, the better solution is to set and get cookie values. Here's two functions to do this:
setCookie = function(){
var args = arguments,
name = (args[0] ? args[0] : '') + '=',
_value = args[1] ? escape(args[1]) : '',
value = _value + ';',
expires = args[2] ? 'expires=' + args[2].toUTCString() + ';' : '',
path = args[3] ? 'path=' + args[3] + ';' : '',
domain = args[4] ? 'domain=' + args[4] + ';' : '',
secure = args[5] ? 'secure;' : '',
newCookie = name + value + expires + path + domain + secure;
document.cookie = newCookie.match(/[a-z||A-Z]/) ? newCookie : ''
return _value;
},
getCookie = function(name){
if(!name || name.replace(/[^a-z|0-9|çáéíóúãõâêîôûàèìòùäëïöü]/,'')=='*') return document.cookie;
var ck = ' ' + document.cookie + ' ',
pos = ck.search(' ' + name + '='),
pos = (pos!=-1) ? pos + 1 : ck.length,
ck = ck.substring(pos-1,ck.length),
end = (ck.search('; ')!=-1) ? ck.search('; ') : ck.length,
value = ck.substring(((ck.search('=')!=-1) ? (ck.search('=')+1) : end),end);
return unescape((value[value.length-1]==' ') ? value.substring(0,value.length-1) : value);
}
They're crossbrowser functions. To use getCookie function, just use the name parameter, and with the setCookie function, use the name,value,expires,path,domain,secure parameters
Related
I am using the functions, SET/Get and check cookie.
The getCookie function, splits the cookie by using(';') it works fine unless I want to save some text which has (';') inside by cookie.
The split function splits the content incorrectly based on (';').
When I change that to something else like ('&') it does not save at all!
Can anyone give an idea what can I use for that?
function setCookie(content, player) {
var d = new Date();
d.setTime(d.getTime() + (365 * 24 * 60 * 60 * 1000));
var expires = "expires=" + d.toUTCString();
document.cookie = player + "=" + content + "; " + expires;
}
//check if the coockie with current player name exists
function checkCookie(player_name) {
var pnote = getCookie(player_name);
alert(pnote);
var delete_cookie = function (player_name) {
document.cookie = player_name + '=;expires=Thu, 01 Jan 1970 00:00:01 GMT;';
};
if (pnote != "") {
$('#tab' + player_name + ' .nicEdit-main').html(pnote);
} else {
if (player_name != "" && player_name != null) {
$('#tab' + player_name + ' .nicEdit-main').prepend("no note");
}
}
}
//Gets the cookie content
function getCookie(player_name) {
var name = player_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);
if (c.indexOf(name) == 0)
return c.substring(name.length, c.length);
}
return "";
}
in setCookie use escape function :
document.cookie = player + "=" + escape(content) + "; " + expires;
and in getCookie use unescape function
return unescape(c.substring(name.length, c.length));
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","/");
I used the following JavaScript to create a pop-up window on the website and for it to show up only once. Now, my client wants a new promotion and I am trying to delete existing cookies and make it pop-up again (so that people who already visited the website, see the pop-up window again, only once like before). Here is the current code:
<!--
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" : "");
document.cookie = curCookie;
}
function setCookie(name, value, expires, path, domain, secure) {
var curCookie = name + "=" + escape(value) +
((path) ? "; path=" + path : "") +
((domain) ? "; domain=" + domain : "") +
((secure) ? "; secure" : "") +
((expires) ? "; expires=" + expires.toGMTString() : "") ;
document.cookie = curCookie;
}
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 unescape(dc.substring(begin + prefix.length, end));
}
function pop()
{
$(document).ready(function() {
$('#myModal').reveal();
});
}
var seen = getCookie("seen");
if (!seen) {
var now = new Date();
now.setTime(now.getTime() + 360000 * 1000);
setCookie("seen", 1, now);
pop();
}
//-->
I tried the following to reset the cookies
<!--
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" : "");
document.cookie = curCookie;
}
function setCookie(name, value, expires, path, domain, secure) {
var curCookie = name + "=" + escape(value) +
((path) ? "; path=" + path : "") +
((domain) ? "; domain=" + domain : "") +
((secure) ? "; secure" : "") +
**";expires=Thu, 01 Jan 1970 00:00:01 GMT";**
document.cookie = curCookie;
}
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 unescape(dc.substring(begin + prefix.length, end));
}
function pop()
{
$(document).ready(function() {
$('#myModal').reveal();
});
}
var seen = getCookie("seen");
if (!seen) {
var now = new Date();
now.setTime(now.getTime() + 1 * 1000);
setCookie("seen", 1, now);
pop();
}
//-->
It's not working. I'm new to JavaScript and would appreciate your help!
I see you have a nice mess so, if I have understood well, this code should do the job:
// on document ready
$(function(){
// check for the old cookie and delete it
if( Cookies.Check('seen') ) Cookies.Set('seen', '', -1); // delete the cookie if it exists
// now work with a new one with other name
if( !Cookies.Check('newmodal') ){ // if the cookie doesn't exist we show the modal and set the cookie
$('#myModal').reveal();
Cookies.Set('newmodal', 'true', 365); // days, if you need to use minutes see the method below
} // there is no `else` here, if the cookie exists nothing happens
});
/**
* Object with methods to manage cookies
* #type Object
*/
var Cookies = {
/**
* Checks if a cookie exists
* #param {String} name
* #return Boolean
*/
Check: function (name) {
return !!this.Get(name);
},
/**
* Gets a cookie value or returns false
* #param {String} name
* #return String|Boolean
*/
Get: function (name) {
var n, ca, c;
n = name + "=";
ca = document.cookie.split(';');
for (var i = 0; i < ca.length; i++) {
c = ca[i].trim();
if (c.indexOf(name) === 0) return c.substring(name.length + 1, c.length);
}
return false;
},
/**
* Sets a cookie
* #param {String} name
* #param {String} value
* #param {Number} [expire]
* #param {Object} [options]
* #return Boolean|void
*/
Set: function (name, value, expire, options) {
var d = new Date(), expires;
var defaults = { expire_in: 'days', path: '/' };
if (typeof options !== "undefined") $.extend(true, defaults, options);
if (expire !== undefined && expire !== null) {
if (defaults.expire_in == 'days') d.setDate(d.getDate() + expire);
else if (defaults.expire_in == 'minutes') d.setDate(d.getTime() + expire * 1000);
else {
throw new JUtils.EX('expire_in configuration is not valid');
}
expires = "expires=" + d.toGMTString();
}
else expires = expires = "";
document.cookie = name + "=" + value + "; " + expires + '; path=' + defaults.path;
return true;
}
};
What i Need:
i Need to use user and evnt_id from cookie.
document.cookie
string :
" country=India; countryCode=IN; __gads=ID=369fde524de77341:T=1417077062:S=ALNI_MakhfG3fYeRIwt9Uw4xSUE8m-2hHw; fbm_172404889604820=base_domain=.10times.com; PHPSESSID=4e467l46efdmvc9vktknod85b2; evnt_id=9; industry=74; evnt_name=India International Trade Fair; evnt_url=iitf; km_ai=jE0JIU3hamljHh0DrWRC%2FR50QNI%3D; km_lv=x; __zlcmid=SAeGECzmK8Nrve; user_flag=2; user=13530767; _ga=GA1.2.1767513107.1417003918; linkedin_oauth_ro57ogahnixy_crc=null; km_uq=; kvcd=1418207265523; _ga=GA1.3.342868374.1416999745; id=13530767; email=afeef1915%40yahoo.com; name=Mohd+Afeef; image_flag=http%3A%2F%2Fgraph.facebook.com%2F100001729894039%2Fpicture".
i need to fetch
user.
event_id from cookie.
code i have tried :
function setCookie(key, value) {
var expires = new Date();
expires.setTime(expires.getTime() + 31536000000); //1 year
document.cookie = key + '=' + value + ';expires=' + expires.toUTCString();
}
function getCookie(key) {
var keyValue = document.cookie.match('(^|;) ?' + key + '=([^;]*)(;|$)');
return keyValue ? keyValue[2] : null;
}
setCookie('evnt_id','evnt_id');
alert(getCookie('evnt_id'));
problem im facing im not able to fetch user and event_id from cookie.
im using symphony framework and need to implement in twig file.
This problem has been solved before. Don't reinvent the wheel :)
I would advise you to read up on cookies: http://www.quirksmode.org/js/cookies.html
The code below comes from that article.
function readCookie(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;
}
console.log(readCookie('evnt_id')); //9
console.log(readCookie('user')); //13530767
document.cookie= "cookiename=cookievalue;
expires=Mon,12Jun2015:00:00:00; path=/;"
I run this script on my Internet Explorer 10 but it doesn't share cookie between 2 IE tab. But when i remove the "expires" properties so it seem to working :
document.cookie= "cookiename=cookievalue ;path=/;"
But i don't want to remove the "expires" properties. So how to resolve this problem ?
2021 update: If you do NOT need to pass information to the server, use localStorage or sessionStorage
I have used this code since mid '90s - it has worked in all browsers on all platforms so far
Include the file and use
setCookie("name","value",expiryDate,"/"); // the last two are optional
// cookie.js file
var cookieToday = new Date();
var expiryDate = new Date(cookieToday.getTime() + (365 * 86400000)); // a year
/* Cookie functions originally by Bill Dortsch */
function setCookie (name,value,expires,path,theDomain,secure) {
value = escape(value);
var theCookie = name + "=" + value +
((expires) ? "; expires=" + expires.toGMTString() : "") +
((path) ? "; path=" + path : "") +
((theDomain) ? "; domain=" + theDomain : "") +
((secure) ? "; secure" : "");
document.cookie = theCookie;
}
function getCookie(Name) {
var search = Name + "="
if (document.cookie.length > 0) { // if there are any cookies
var offset = document.cookie.indexOf(search)
if (offset != -1) { // if cookie exists
offset += search.length
// set index of beginning of value
var end = document.cookie.indexOf(";", offset)
// set index of end of cookie value
if (end == -1) end = document.cookie.length
return unescape(document.cookie.substring(offset, end))
}
}
}
function delCookie(name,path,domain) {
if (getCookie(name)) document.cookie = name + "=" +
((path) ? ";path=" + path : "") +
((domain) ? ";domain=" + domain : "") +
";expires=Thu, 01-Jan-70 00:00:01 GMT";
}
The following sample code will demonstrate setting a cookie of your choosing directly, without requiring input from the user. To store a cookie from your site, simply put a call to the javascript function in your HTML page, like this:
<script type="text/javascript">cookieSet();</script>
The real work is done by the cookieSet() javascript function, which can be either in the area of your HTML page, or in a separate javascript file:
var cookieText = "Put your desired cookie value here";
var cookiePrefix = "";
var myPage = location.href;
var wwwFlag = myPage.indexOf('www');
if (wwwFlag > 0) {
cookiePrefix = "www";
}
var cookieName = cookiePrefix + "cbCookie";
function cookieSet() {
if (document.cookie != document.cookie) {
index = document.cookie.indexOf(cookieName);
} else {
index = -1;
}
if (index == -1) {
document.cookie=cookieName+"="+cookieText+"cbEndCookie; expires=Monday, 04-Apr-2020 05:00:00 GMT";
}
}