简体   繁体   English

window.onbeforeunload仅在刷新页面后有效

[英]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 我有一个名为login_check.cfm的页面,此页面对home.cfm执行了location.href

inside the home.cfm i have this code 在home.cfm中,我有此代码

<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. 问题是我的页面是基于90%的Ajax,并且用户点击后退按钮时返回的登录页面最多。

use Document ready() make no difference. 使用Document ready()没什么区别。

suggestions ? 建议?

i found this old Question where rohit416 give a good answer and it still works 我发现这个老问题rohit416给出了很好的答案 ,它仍然有效

(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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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