Nando @ Aria Media

( learning Clojure ColdFusion Lucee Javascript jQuery Angular CSS Linux Apache HTML5 & etc )

Disabling Browser Back Button

| Comments

I’m working on a particular process in a web application where the user could unintentionally create duplicate content using the browser back button. Here’s a handy way I ran across to disable the back button, or indeed handle it in any way needed.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
window.onload = function () {
    if (typeof history.pushState === "function") {
        history.pushState("jibberish", null, null);
        window.onpopstate = function () {
            history.pushState('newjibberish', null, null);
            // Handle the back (or forward) buttons here
            // Will NOT handle refresh, use onbeforeunload for this.
            alert('Back button disabled. Please use navigation links instead.');
        };
    }
    else {
        var ignoreHashChange = true;
        window.onhashchange = function () {
            if (!ignoreHashChange) {
                ignoreHashChange = true;
                window.location.hash = Math.random();
                // Detect and redirect change here
                // Works in older FF and IE9
                // * it does mess with your hash symbol (anchor?) pound sign
                // delimiter on the end of the URL
                alert('Back button disabled. Please use navigation links instead.');
            }
            else {
                ignoreHashChange = false;
            }
        };
    }
}

Apparently, this works with older browsers that do not support HTML5.

Source: http://stackoverflow.com/questions/6359327/detect-back-button-click-in-browser

Comments