Cookies saved using document.cookie getting deleted after closing the browser - javascript

Using the common code for setting the username and password in cookie via javascript as below -
function submitLogin(){
var uNameInCookie=checkCookie("username");
var passInCookie=checkCookie("password");
if(uNameInCookie!=="" && passInCookie!=""){
document.loginForm.login.value=uNameInCookie;
document.loginForm.passwd.value=passInCookie;
document.loginForm.submit();
}
else{
if(checkInput()){
document.loginForm.submit();
}
}
}
function checkCookie(property){
var x= property;
var prop = getCookie(x);
return prop;
}
function getCookie(cName){
var name = cName + "=";
var cookiez = document.cookie.split(';');
for ( var i=0;i<cookiez.length;i++){
var c= cookiez[i].trim();
if(c.indexOf(name)==0){
return c.substring(name.length,c.length);
}
}
return ""
}
function checkInput()
{
if (document.loginForm.login.value == "")
{
return false;
}
else if (document.loginForm.passwd.value == "")
{
return false;
}
if (document.loginForm.login.value!= "" && document.loginForm.login.value!=null)
{
var usernameValue=document.loginForm.login.value;
setCookie("username",usernameValue,365);
}
if (document.loginForm.passwd.value!= "" && document.loginForm.passwd.value!=null)
{
var passwordValue=document.loginForm.passwd.value;
setCookie("password",passwordValue,365);
}
return true;
}
function setCookie ( cName, cValue, expDays){
var d = new Date();
d.setTime(d.getTime() + (expDays*24*60*60*1000));
var expDate = d.toGMTString();
alert(expDate);
document.cookie = cName + "=" + cValue + ";" + expDate + ";path=/";
}
window.onload=submitLogin();
</script>
the browser is able to auto login the details and submit the form only when I do a logout.
But if I close the browser and hit the url ,the username and password stored in cookie is gone and the form does not auto login.
Is there anything wrong with the code or is it some kind of browser setting. I have added the specific site also to add cookies if needed. Is there anything else that we need to do?
Thanks in advance.

The reason is when you are setting the cookie it's expiration date is not set and it's taking cookie for Session scope. Make correct the following line:
document.cookie = cName + "=" + cValue + "; expires=" + expDate + ";path=/";

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.

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

When I add a certain line to my Javascript code it removes the onclick function I have for my HTML function.

I am coding a game and I need to save some variables with cookies. I added a line that should execute a Javascript function that will check if the user has already been on the website and made an account or not, and if they have not it will ask for a username. However, when I added the line that should run the function, the function after it failed, and so did it.
This is a portion of my code:
<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=/";
}
function checkCookie() {
var username=getCookie("username");
if (username!="") {
alert("Welcome again " + username);
} else {
username = prompt("Please enter your username:", "");
if (username != "" && username != null) {
setCookie("username", username, 365);
}
}
}
</script>
<button id="open_market">Market</button>
<script>
checkCookie();
open_market.onclick = function() {
window.open("https://thenumnut.github.io/Wars-of-Shares/Market");
}
</script>
The line that I added to run the function was "checkCookie();". After I added that line the button with id "open_market" would not respond when clicked. This makes me think that the code failed/crashed on the line before it when I said "checkCookie();".
If anybody can find the problem with this code I will greatly appreciate it. You can see in the code the github link to my code on github if you would like to see my full code.
I added your getCookie() function, and apart from that, just added a bit of HTML around the tags, and here's the code:
<!DOCTYPE html> <html> <head> <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 ""; }
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=/"; } function checkCookie() {
var username=getCookie("username");
if (username!="") {
alert("Welcome again " + username);
} else {
username = prompt("Please enter your username:", "");
if (username != "" && username != null) {
setCookie("username", username, 365);
}
} } </script> </head> <body> <button id="open_market">Market</button> <script> checkCookie(); open_market.onclick = function() { window.open("https://thenumnut.github.io/Wars-of-Shares/Market"); } </script> </body> </html>
It seems to be working fine
In JavaScript this is often a sign, that there is a bug in checkCookie();. I don't see one at first glance, but your browser should show you the bug in his console.
You can open the console in most browsers (e.g. Firefox, IE) by rightclicking somewhere on your page and then choose "Inspect Element". Now change to the tab Console.
If you don't understand the error message, just post it here
Open your browser's developer tools. Read the error message
checkCookie(); calls a function which has var username=getCookie("username");.
You haven't defined a getCookie function, so it throws an exception and stops execution.

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>

Javascript cookies code not working

I was writing this code that is based on a tutorial and on the tutorial the code works, but when I try to do it by myself it doesn't. Can you help me ?
The code : (Tutorial Link).
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
var user_name;
var expires = new Date();
if ((document.cookie == "") == false)
{
var length = document.cookie.length - 1;
var message = document.cookie.substr(5, length);
document.write("<h2><center>Welcome back, " + message + "</center></h2>");
}
function check()
{
user_name = document.getElementById("name").value;
expires.setFullYear(expires.getFullYear() + 1);
document.cookie = escape("name") + escape(user_name) + "; expires = " + expires.toGMTString();
alert(document.cookie);
}
</script>
<meta charset="utf-8">
<title></title>
</head>
<body>
Name: <input type="text" id="name" />
<input type="button" value="Enter" onClick="check()" />
</body>
</html>
Because you've mentioned I was creating this code that is tutorial based and on the tutorial, so if it's just for a test myself thing then you may consider to use this one (Demo Here), just enter a name and value for the cookie in the cookie name and cookie value fields respectively, when you want to Add a new cookie and to Delete a cookie just enter the name of the cookie in the cookie name field and same for View, you can add a Delete All buttons only by splitting cookies using & and making a loop and calling the eraseCookie() function, try it yourself.
Also there are already better ones are available on the web to use in the real case, but this one is not bad at all.
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=/";
return true;
}
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) {
if(!name) {
alert('\nPlease enter the name of cookie in cookie the name field.');
return false;
}
if(readCookie(name)){
if(createCookie(name,"",-1)) {
alert('Cookie "' + name + '" has been deleted!');
}
}
else alert('Cookie "' + name + '" doesn\'t exist!');
}
function addCookie()
{
cookie_name = document.getElementById("cName").value.replace(/^\s+|\s+$/g,'');
cookie_value = document.getElementById("cValue").value.replace(/^\s+|\s+$/g,'');
if(cookie_name.length && cookie_value.length){
createCookie(cookie_name, cookie_value, 7);
alert("New cookie has been added, \ncookie name : " + cookie_name + "\ncookie value : " + cookie_value);
}
else{
alert("Please enter a name and value for the cookie.");
}
}
function showCookie(name)
{
if(!name) {
alert('\nPlease enter the name of cookie in the cookie name field.');
return false;
}
var val = readCookie(name);
if(val){
alert(readCookie(name));
}
else alert('Cookie "' + name + '" doesn\'t exist!');
}
// Onload to check and greet
if(name = readCookie('name')) alert('Welcome back, ' + name);
Example Here.

Categories