简体   繁体   English

使用Javascript在页面刷新时调用函数

[英]Call a function on page refresh using Javascript

function warnuser()
{
    return "Don't refresh the page.";
}

window.onbeforeunload = warnuser;

If the user refreshes the page and the user clicks 'leave this page' on confirmation box, i want to call a javascript function , otherwise not! 如果用户刷新页面并且用户在确认框上单击“离开此页面”,我想调用javascript函数,否则不会! I am confused about how to do that. 我对如何做到这一点很困惑。 Thank you 谢谢

You need to intercept the F5 key press and setup the onbeforeunload handler only in that case: 您需要拦截F5键按下并仅在这种情况下设置onbeforeunload处理程序:

document.addEventListener('keydown', function(e) {
    if(e.which == 116) {
        window.onbeforeunload = function() {
            window.onbeforeunload = null;
            return "Do you really want to refresh the page?";
        }
    }
}, false);

Demo: http://jsfiddle.net/ejDrq/ 演示: http//jsfiddle.net/ejDrq/

Note that this does not work if the user clicks the Refresh button. 请注意,如果用户单击 “刷新”按钮,则不起作用。 It is impossible to intercept this. 拦截这个是不可能的。

If you have control of the server side which is hosting the page then you can handle this logically with a semaphore ( wiki:semaphore ). 如果您可以控制托管页面的服务器端,那么您可以使用semaphorewiki:semaphore )在逻辑上处理它。 Basically it is a spinning lock which would be implemented in their server side session. 基本上它是一个旋转锁,它将在他们的服务器端会话中实现。 Resetting the page state if they have entered and not exited in a safe manner. 如果页面状态已进入且未以安全方式退出,则重置页面状态。 Naturally, as with all spinning locks, there would have to be a safe state to clear the lock out. 当然,与所有旋转锁一样,必须有一个安全状态来清除锁定。

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

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