Session Only Cookie Javascript - javascript

This Javascript cookie script works great so far, you just adjust when you would like the cookie to expire in the (expiresDays*24) line. However, I would like the cookie to expire when the browser is completely closed, but the cookie to persist whilst you are still on the site, even if you go to another webpage or reload the home page. I read this is doable and can be done with session cookies, by setting the value to 0 or no value, but being a learner on javascript, I am not sure how to do it, do any more experienced programmers know how to adjust the script below to do what I would like?
<script type="text/javascript">
function setCookie(cookieName, cookieValue, expireDays,isGlobal) {
var expireDate = new Date();
expireDate.setTime(expireDate.getTime() +
(expireDays*24*60*60*1000));
var expires = "expires="+expireDate.toUTCString();
if(isGlobal){
document.cookie = cookieName + "=" + cookieValue + "; " +
expires+"; path=/";
}else{
document.cookie = cookieName + "=" + cookieValue + "; " +
expires;
}
}
function getCookie(cookieName) {
var name = cookieName + "=";
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(cookieName) {
if (getCookie(cookieName) != "") {
return true;
} else {
return false;
}
}
</script>

I fixed this issue, all that was needed was to replace the values in this line:
from (expireDays*24*60*60*1000))
and change to:
(expireDays"=0"))
otherwise I left the scrip unchanged, the cookies lasts the duration of the visit to the website, including if you navigate around the site. But if you completely close the browser, the cookie expires.

Related

How To set Cookie To expire when tab is closed

I'm trying to create a session cookie for my media player here in order to track usage and other things the code and the code snippet below isn't creating it at all, (by the way, i'm using one script to create multiple cookies using parameters and want to keep it like that to prevent lengthily scripts)
I've tried a lot of the answers provided in the website already but they don't work, they just result in the same problem
//script to create the cookies
function setCookie(cname,cvalue,exdays) {
var d = new Date();
d.setTime(d.getTime() + (exdays*24*60*60*1000));
var expires = "expires=" + d.toGMTString();
document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/";
}
//for the cookie that makes the name, not part of the question
function getCookie(cname) {
var name = cname + "=";
var decodedCookie = decodeURIComponent(document.cookie);
var ca = decodedCookie.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 "";
}
// also for the name
function checkCookie() {
var user=getCookie("username");
if (user != "") {
document.getElementById("display").innerHTML = "Welcome back " + user
} else {
document.getElementById("display").innerHTML = "Please enter your name in The prompt at the top of your screen!";
user = prompt("Please enter your name:","");
if (user != "" && user != null) {
setCookie("username", user, 30);
}
}
}
window.onload = checkCookie()
//for the session
window.onload = createsession()
function createsession(length){
var sessionnumber = Random rand = new Random();
long drand = (long)(rand.nextDouble()*10000000000L);
setCookie("session", sessionnumber);
};
window.onbeforeunload = function(){
document.cookie = "username=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;";
};
what I want is for the script to create a cookie that expires at end of the browser session, while being able to keep the other scripts the same to allow me to create multiple cookies without making duplicates of those processing scripts
I created the following fiddle for testing: https://jsfiddle.net/Twisty/toxjLmd8/10/
I added a few things to increase info in console. When I inspect the page and view Storage I can see session cookie and username cookie. If I refresh, I am prompted to enter name again. So it seems to be working as expected.
$(function() {
function setCookie(cname, cvalue, exdays) {
var d = new Date();
if (exdays == undefined) {
exdays = 1;
}
d.setTime(d.getTime() + (exdays * 24 * 60 * 60 * 1000));
var expires = "expires=" + d.toGMTString();
console.log("Set Cookie: " + cname + "=" + cvalue, expires);
document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/";
}
function getCookie(cname) {
var name = cname + "=";
var decodedCookie = decodeURIComponent(document.cookie);
var ca = decodedCookie.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 false;
}
function checkCookie() {
var user = getCookie("username");
if (user != "") {
$("#display").html("Welcome back " + user);
} else {
$("#display").html("Welcome, please enter your name.");
user = prompt("Please enter your name:", "");
if (user != "" && user != null) {
setCookie("username", user, 30);
}
}
}
function newSession() {
var sessionnumber = Math.random() * 10000000000.0;
console.log("New Session: " + sessionnumber);
setCookie("session", sessionnumber, 0.0125);
}
function checkSession() {
if (getCookie("session") == false) {
newSession();
}
console.log("Current Session: " + getCookie("session"));
}
window.onbeforeunload = function() {
console.log("Closing - Expire 'username' Cookie");
setCookie("username", "", 0);
};
window.onload = checkCookie();
window.onload = checkSession();
});
Setting a past date or current date and time should have the browser expire the cookie right away and drop it. Setting a cookie with no expiration date can have unexpected results from different browsers. If the date is not set it should expire at the end of the session (the expected behavior) yet the browser may see that it has already expired (still good) or will never expire (really not good). Not all browsers are written the same.
Also if onbeforeunload callback is not triggered, the cookie is not expired but would remain active for 30 days per checkCookie(). You could set the cookie to expire in 20 min (0.0125 days). This is how sessions are handled on the server-side. If the socket closes and the session is idle for 20 min (the default for Session Idle Timeout), the session data is dropped.
Hope this helps.

How do I display cookies on other pages?

I am learning about cookies and JavaScript for a student project and have attempted to use them in a school project. However, I have stumbled onto a problem when I try to implement a simple function which bookmarks articles.
This is the code which I place in an article. When I press the bookmark icon, the function below is triggered, creating a cookie that expires after 14 days.
<script>
function showBookmark() {
document.getElementById("bookmark").innerHTML = "bookmark";
var d = new Date();
d.setTime(d.getTime() + (14*24*60*60*1000));
var expires = "expires="+ d.toUTCString();
document.cookie = "cookie1" + "=" + "Article 1 - Title Of Article 1" + ";" + expires + ";path=/";
};
</script>
This is the code which I place in the page where I store and display all the bookmarks the user has made. The code scans through 20 cookies ("cookie1", "cookie2" to "cookie20") and then displays the first 10 cookies where there is a value. The cookies are then displayed in a table using innerHTML().
<script>
function getCookie(cname) {
var name = cname + "=";
var decodedCookie = decodeURIComponent(document.cookie);
var ca = decodedCookie.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);
} else {
return "false"
}
}
};
var counter=0;
for (var alpha=0; alpha<20; alpha++){
bookmark = getCookie("cookie"+alpha.toString());
if (counter > 10){
break;
}
if (bookmark != "false"){
document.getElementById("bookmark"+counter.toString()).innerHTML = bookmark;
counter++;
}
};
</script>
However, for some reason the code above does not display the intended result (the name of the article does not appear on the page with all the bookmarks even after pressing the icon and triggering the getCookie function). Is there something wrong with my code?
(This is the first question I am asking so any advice would be greatly appreciated)

cookies aren't being stored after page change

I am storing cookies from form values using the below code. I can see that the cookies have been stored when I look under Application > Cookies in developer tools. When you press submit on this form, it takes you to the start of a survey. The pages of the survey are within the same file path of the form page. After the first page of the survey loads, I check in developer tools and the cookies aren't there. This only happens randomly, but I've found that it happens much more often on Macbooks using Chrome. I am on a pc using chrome and it's never happened to me.
// Script to set cookies
function setCookie(cname,cvalue,exdays) {
var d = new Date();
d.setTime(d.getTime() + (exdays*24*60*60*1000));
var expires = "expires=" + d.toGMTString();
document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/";
}
// Script to get cookies
function getCookie(cname) {
var name = cname + "=";
var decodedCookie = decodeURIComponent(document.cookie);
var ca = decodedCookie.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 "";
}
//Check for enabled cookies
function areCookiesEnabled() {
document.cookie = "__verify=1";
var supportsCookies = document.cookie.length >= 1 &&
document.cookie.indexOf("__verify=1") !== -1;
var thePast = new Date(1976, 8, 16);
document.cookie = "__verify=1;expires=" + thePast.toUTCString();
return supportsCookies;
}
//Set cookies on form submission
$(document).ready(function() {
$( "#fn-2" ).change(function() {
setCookie("firstName", this.value, 30; path=appfire.com/club);
});
$( "#ln-2" ).change(function() {
setCookie("lastName", this.value, 30);
});
$( "#eml-2" ).change(function() {
setCookie("email", this.value, 30);
});
});
$("#wf-form-club_profile_creator").submit(function(e){
e.preventDefault();
if (areCookiesEnabled() ) {
console.log('Cookies are enabled.');
window.location.replace("http://www.appfire.com/club/quiz/q1");
} else {
console.log('Cookies are disabled');
alert('Cookies appear to be disabled in your browser. To create your A List club profile, please enable cookies and try again. Thanks!');
window.location.replace("http://www.appfire.com/club");
}
});

how to know if a user has a certain cookie using javascript

I have been stuck on this problem for a couple hours now, and cant seem to get off of it. I have a html website where i'm giving a user a cookie called "schoolid" and it has the school's ID in it. If a user has a certain school ID, in this case "gms08",they will be redirected to another website. This is what i have so far in the cookie area.
I have a check cookie function checking to make sure the user has it, but i cant seem to get it to pick up on the fact that the user has the cookie and it is gms08.
i.stack.imgur.com/wQjnx.png
Pastebin: http://pastebin.com/Gfjc7iTG
<script>
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 + ";path=/";
}
</script>
<script>
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 "";
}
</script>
<script>
function checkCookie() {
var id = getCookie("schoolid");
if (id != "") {
alert("Welcome again ");
} else {
alert("user");
}
}
</script>

Load lightbox every 'x' amount of page loads

I am using a jQuery Colorbox onLoad lightbox which works no problem.
This is the code so far, I was wondering how to make the lightbox appear every 5 page loads (for example). So as the user is browsing the site, every 5th page they visit the lightbox appears.
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript" src="res/jquery.colorbox-min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
setTimeout(function() {
$.fn.colorbox({href:"xxxxx.jpg", open:true});
}, 1500);
});
</script>
Thanks, any help is appreciated, even if you can point me in the right direction.
Generally you would have to keep track of the page load count. Like Anthony suggested, you should keep it in a cookie.
I found two functions online to handle cookies: cname = cookie name, cvalue is what you save in the cookie, and milliseconds is for how long the cookie is valid;
function setCookie(cname, cvalue, milliseconds) {
var d = new Date();
d.setTime(d.getTime() + (milliseconds));
var expires = "expires=" + d.toGMTString();
document.cookie = cname + "=" + cvalue + "; " + expires;
}
function getCookie(cname) {
var name = cname + "=";
var ca = document.cookie.split(';');
for (var i = 0; i < ca.length; i++) {
var c = ca[i].trim();
if (c.indexOf(name) == 0) return c.substring(name.length, c.length);
}
return "";
}
So what you would want to do is every page load retrieve a cookie with the count and increase it:
var _pageloads = getCookie("PageLoadCount");
if(_pageloads=="")
{
_pageloads=0;
}
_pageloads +=1;
if(_pageloads ==5){
_pageloads =0; //reset your counter
//pop up the lightbox
}
setCookie("PageLoadCount",_pageloads,1 * 60 * 1000); //make cookie valid for one hour

Categories