简体   繁体   中英

window.onbeforeunload only works after i refresh the page

note: i see this Question but the problem is not the same.

I have one page named login_check.cfm and this page do a location.href to home.cfm

inside the home.cfm i have this code

<script>
window.onbeforeunload = function() { window.history.go(0); };
</script>

or

<script>
window.onbeforeunload = function() { window.history.forward(1); };
</script>

my intention is to prohibit the User to use the back button, and its work, but only a do a refresh or use a link to do refresh. the problem is my page is 90% ajax based and the most off the user go back to login page when they clicked backbutton.

use Document ready() make no difference.

suggestions ?

i found this old Question where rohit416 give a good answer and it still works

(function ($, global) {

    var _hash = "!",
    noBackPlease = function () {
        global.location.href += "#";

        setTimeout(function () {
            global.location.href += "!";
        }, 50);
    };

    global.setInterval(function () {
        if (global.location.hash != _hash) {
            global.location.hash = _hash;
        }
    }, 100);

    global.onload = function () {
        noBackPlease();

        // disables backspace on page except on input fields and textarea.
        $(document.body).keydown(function (e) {
            var elm = e.target.nodeName.toLowerCase();
            if (e.which == 8 && elm !== 'input' && elm  !== 'textarea') {
                e.preventDefault();
            }
            // stopping event bubbling up the DOM tree..
            e.stopPropagation();
        });
    }

})(jQuery, window);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM