Search code examples
javascripthtmlwindowlocation

JavaScript window.location not redirecting to a different page


This is a snippet of my `index.html

<div class="maincontainer">
    <h2 id="heading" class="heading"></h2>
    <input type="button" id="resetPassword" class="resetPassword" onclick="resetPassword()" value= "Reset Password" />
    <form method="post" onsubmit="return submitform()">
        <div>
            <input type="password" id="password" name="password" class="patternlock" />
            <input type="submit" value="login"/>
        </div>
    </form>
</div>

This is a snippet of my script.js which I included in my index.html

function submitform(){
var passwordvalue = document.getElementById("password").value;
var digits = getlength(passwordvalue);
if(digits<5) {
    raiseerror("lengthTooSmall");
}

checkduplicatedigits(passwordvalue);

if (errorraised == false && passwordset == false) {
    localStorage.setItem("passwordvalue", passwordvalue);
    successmessage("patternStored");
}
else if ( errorraised == false && passwordset == true) {
    if (localStorage.getItem("passwordvalue") == passwordvalue) {
        successmessage("screenUnlocked");
    }
    else {
        raiseerror("IncorrectPattern");
    }
}
return true;
};

function successmessage(successcode) {
    if(successcode == "screenUnlocked") {
        alert("You have unlocked the screen!");
        window.location = "./welcome.html";  //bug to be fixed
    }
    if (successcode == "patternStored") {
        alert("Your pattern is stored. Thanks.");
        passwordset = true; 
    }
    if (successcode == "resetSuccess") {
        alert("Pattern Reset Success!");
    }
    location.reload();
};

Here whenever, successcode == "screenUnlocked" is triggered, I am able to get the alert message

alert("You have unlocked the screen!");

but the next line

window.location = "./welcome.html";

is not working.

Why isn't it working in this case? Are there any specific requirements for window.location to work? If so, please specify.

Checked this code on Google Chrome 39.0.2171.71. I have checked my console for errors but there aren't any. There are only a few warnings but they are not related to this.

Or are there any other functions to make a redirection using pure Javascript? If so, please specify.

Please comment if any further information is required.


Solution

  • First, this is not secure so I hope this is not for real protection.

    The reason why it fails is you have a race condition with window.location and the form submission. The form is submitting because you are not cancelling the form submission.

    You need to return false, not true at the end of the validation function.