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;
}
};
Related
Im trying to create my own analytics script for my website, and for this I have tried to put together a way to create userID and sessionID.
But I am not sure if I have done it correctly.
I'm trying to:
Check to see if user has set a userID - if not set it.
check to see if user has a sessionID - it not set it.
the userID is set to follow the user, where the user continues to hold the userID on several visits, where the sessionID is unique for each visit.
if (getCookie('yb_uid') != null) {
if (getCookie('yb_sid') != null) {
setCookie('yb_uid', getCookie('yb_uid'), 730);
setSessionCookie(getCookie('yb_sid'));
} else {
setCookie('yb_uid', getCookie('yb_uid'), 730);
setSessionCookie(setSID());
}
} else {
setCookie('yb_uid', setUID(), 730);
setSessionCookie(setSID());
}
if (getCookie('yb_sid') == null || getCookie('yb_sid') ==
'undefined' || !getCookie('yb_sid')) {
setSessionCookie(setSID());
}
function setUID() {
return "ybID#" + _setID(5) + "-" + _setID(5) + "-" + Date.now();
}
function setSessionCookie(value) {
var now = new Date();
var minutes = 30;
now.setTime(now.getTime() + (minutes * 60 * 1000));
document.cookie = "yb_sid=" + value + "; max-age=" + now.toUTCString() + "; expires=" + now.toUTCString() + "; path=/";
} /*set session cookie*/
function getCookie(name) {
var re = new RegExp(name + "=([^;]+)");
var value = re.exec(document.cookie);
return (value != null) ? unescape(value[1]) : null;
} /* get cookie value */
function _setID(length) {
var result = '';
var characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
var charactersLength = characters.length;
for (var i = 0; i < length; i++) {
result += characters.charAt(Math.floor(Math.random() * charactersLength));
}
return result;
}
function setSID() {
var ts = Math.round(+new Date() + Math.random() / 1000);
return ts;
}
function setCookie(name, value, days) {
if (days) {
var date = new Date();
date.setTime(date.getTime() + days * 24 * 60 * 60 * 1000);
var expires = "; max-age=" + date.toGMTString() + " expires=" + date.toGMTString();
} else {
var expires = "";
}
document.cookie = name + "=" + value + expires + ";path=/";
Maybe this has an even easier way to script it?
Have you tried UUID https://www.npmjs.com/package/uuid for generating an user id?
So I am new to JavaScript and I'm kinda stuck.
I want to allow my cookie to work on all of my pages.
I know that I need to add "/" to path. The only problem is that the little script I got is a bit different than all the examples out there.
Does somebody know where to put it?
var expdate = new Date();
expdate.setTime(expdate.getTime() + (24 * 60 * 60 * 1000 * 365));
function setCookie(name, value, expires, path, domain, secure) {
var thisCookie = name + "=" + escape(value) + ((expires) ? "; expires=" +
expires.toGMTString() : "") + ((path) ? "; path=" + path : "") + ((domain) ? ";domain=" + domain : "") + ((secure) ? "; secure" : "");
document.cookie = thisCookie;
}
function showCookie() {
alert(unescape(document.cookie));
}
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(name) {
var arg = name + "=";
var alen = arg.length;
var clen = document.cookie.length;
var i = 0;
while (i < clen) {
var j = i + alen;
if (document.cookie.substring(i, j) == arg) return getCookieVal(j);
i = document.cookie.indexOf(" ", i) + 1;
if (i === 0) break;
}
return null;
}
function MyNamer() {
var now = new Date();
now.setTime(now.getTime() + 365 * 24 * 60 * 60 * 1000);
var username = GetCookie("username");
if ((!username) || (username == 'null')) {
username = prompt("What is your name?:", "");
}
setCookie("username", username, now);
if (username) {
document.write(username);
setCookie("username", username, now);
} else
document.write("Guest")
}
Thanks in advance!
Well, from your code it looks like the 4th argument in setCookie is the one you want:
setCookie(name, value, expires, path, domain, secure)
e.g.setCookie("myCookie", "myCookieValue", new Date(), "/")
What are you using the cookie for? The webserver you're making the request from controls cookie data, including path. If you're just storing data then you could use the browsers' local/session storage objects?
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","/");
Here's what I hope is a quick question...
I am trying to set a cookie that can be used sitewide. I'm creating a lead generation type site. I want users to fill out a form in order to access exclusive information. Once they fill out the form, they have access to the info.
I am dropping a cookie when they user submits the form so that they can just get straight to the content the next time they visit the site. The form they fill out is in the sidebar of every page on the site. When the user fills out the form on one page, they shouldn't see it on ANY page of the site.
Everything is working, except for the sitewide bit. I think the issue is in this bit of code:
function set_cookie(name, value, expires, path, domain, secure){
if (!expires){expires = new Date()}
document.cookie = name + "=" + escape(value) +
((expires == null) ? "" : "; expires=" + expires.toGMTString()) +
((path == null) ? "" : "; path=" + path) +
((domain == null) ? "" : "; domain=" + domain) +
((secure == null) ? "" : "; secure");
}
But here's the full code below. THANKS SO MUCH!
<script type="text/javascript">
<!--
cookie_name="landasp"
expdays=365
// An adaptation of Dorcht's cookie functions.
function set_cookie(name, value, expires, path, domain, secure){
if (!expires){expires = new Date()}
document.cookie = name + "=" + escape(value) +
((expires == null) ? "" : "; expires=" + expires.toGMTString()) +
((path == null) ? "" : "; path=" + path) +
((domain == null) ? "" : "; domain=" + domain) +
((secure == null) ? "" : "; secure");
}
function get_cookie(name) {
var arg = name + "=";
var alen = arg.length;
var clen = document.cookie.length;
var i = 0;
while (i < clen) {
var j = i + alen;
if (document.cookie.substring(i, j) == arg){
return get_cookie_val(j);
}
i = document.cookie.indexOf(" ", i) + 1;
if (i == 0) break;
}
return null;
}
function get_cookie_val(offset){
var endstr = document.cookie.indexOf (";", offset);
if (endstr == -1)
endstr = document.cookie.length;
return unescape(document.cookie.substring(offset, endstr));
}
function delete_cookie(name,path,domain){
document.cookie = name + "=" +
((path == null) ? "" : "; path=" + path) +
((domain == null) ? "" : "; domain=" + domain) +
"; expires=Thu, 01-Jan-00 00:00:01 GMT";
}
function saving_cookie(){
var expdate = new Date ();
expdate.setTime (expdate.getTime() + (expdays*24*60*60*1000*30)); //set for one month
Data="cooked"
set_cookie(cookie_name,Data,expdate)
}
function get_cookie_data(){
inf=get_cookie(cookie_name)
if(!inf){
document.getElementById("display1").style.display="block"
}
else{
document.getElementById("display2").style.display="block"
}
}
// -->
</script>
You should specify a site wide path, if the path is not given:
((path == null) ? "; path=/" : "; path=" + path) +
You can debug the cookies using Firebug, just have a look at the set cookies.
For some reason this script gets stuck in a redirection loop and wont let you leave "android.html". The url bar shows it is trying to go to "index.html" but it just flashes then stays on "android.html"
var caution = false
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" : "")
if (!caution || (name + "=" + escape(value)).length <= 4000)
document.cookie = curCookie
else
if (confirm("Cookie exceeds 4KB and will be cut!"))
document.cookie = curCookie
}
function getCookie(name) {
var prefix = name + "="
var cookieStartIndex = document.cookie.indexOf(prefix)
if (cookieStartIndex == -1)
return null
var cookieEndIndex = document.cookie.indexOf(";", cookieStartIndex + prefix.length)
if (cookieEndIndex == -1)
cookieEndIndex = document.cookie.length
return unescape(document.cookie.substring(cookieStartIndex + prefix.length, cookieEndIndex))
}
function deleteCookie(name, path, domain) {
if (getCookie(name)) {
document.cookie = name + "=" +
((path) ? "; path=" + path : "") +
((domain) ? "; domain=" + domain : "") +
"; expires=Thu, 01-Jan-70 00:00:01 GMT"
}
}
function fixDate(date) {
var base = new Date(0)
var skew = base.getTime()
if (skew > 0)
date.setTime(date.getTime() - skew)
}
var now = new Date()
fixDate(now)
now.setTime(now.getTime() + 365 * 24 * 60 * 60 * 1000)
var visits = getCookie("indexVisited")
if (!visits)
window.location.replace("./android.html");
else
window.location.replace("./index.html");
setCookie("indexVisited", visits, now)
Besides missing a whole lot of semicolons, your code tries to set the cookie after it redirects to another page. Javascript stops executing upon a redirect, so your setCookie call never gets executed. Try moving it up before the redirects.