0

I am building a web application where I need to prevent back navigation in the browser history. After searching the threads in StackOverflow I found this:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<title>Untitled Page</title>
<script type = "text/javascript" >
function changeHashOnLoad() {
     window.location.href += "#";
     setTimeout("changeHashAgain()", "50"); 
}

function changeHashAgain() {
  window.location.href += "1";
}

var storedHash = window.location.hash;
window.setInterval(function () {
    if (window.location.hash != storedHash) {
         window.location.hash = storedHash;
    }
}, 50);
</script>
</head>
<body onload="changeHashOnLoad(); ">
Try to hit the back button!
</body>
</html>

Reference Disable browser's back button

I did not change anything in the JavaScript. However, after using this in my code, I am observing another problem while the page is being visited. The webpage is getting auto-scrolled to the top prohibiting viewing the bottom part of the page alongwith disabling of some other features also.

The interesting part is that the page is not showing this symptom when I manually hit the refresh button. I am not getting what is causing this issue.

See, my basic requirement is to stop users visiting the previous page. If any other alternative is there, that would also be welcome.

Please help me to fix this. Thanks in advance.

Community
  • 1
  • 1
samlancer
  • 141
  • 2
  • 13
  • Since Javascript is run on the client-side they can just edit your script live if they feel like it, you cannot effectively stop a user from using browser's built-in functionality. – Etheryte Apr 12 '15 at 13:40

2 Answers2

2

I have modified code. Now its works in all modern browsers, IE8 and above

var storedHash = window.location.hash;
function changeHashOnLoad() {
    window.location.href += "#";
    setTimeout("changeHashAgain()", "50");
}

function changeHashAgain() {
    window.location.href += "1";
}

function restoreHash() {
    if (window.location.hash != storedHash) {
        window.location.hash = storedHash;
    }
}

if (window.addEventListener) {
    window.addEventListener("hashchange", function () {
        restoreHash();
    }, false);
}
else if (window.attachEvent) {
    window.attachEvent("onhashchange", function () {
        restoreHash();
    });
}
$(window).load(function () { changeHashOnLoad(); });
Vishnu T S
  • 105
  • 8
1

You are basically reloading the page every 50 ms through

window.location.href += "#";
window.location.href += "1";

Since the browser reloads when the location.href attribute changes.And you call that method again after that reload.

So the site starts to display at the top again every time.

You might generate the hash within a variable and use that for comparison i guess.

Jonas Krispin
  • 136
  • 1
  • 6