Question

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.

Was it helpful?

Solution

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=/";
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top