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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11285908/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 12:38:34  来源:igfitidea点击:

Call a function on page refresh using Javascript

javascriptonbeforeunload

提问by Rajat Shah

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! I am confused about how to do that. Thank you

如果用户刷新页面并且用户在确认框中单击“离开此页面”,我想调用一个 javascript 函数,否则不会!我对如何做到这一点感到困惑。谢谢

采纳答案by ThiefMaster

You need to intercept the F5key press and setup the onbeforeunloadhandler 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 clicksthe Refresh button. It is impossible to intercept this.

请注意,如果用户单击“刷新”按钮,这将不起作用。这是不可能拦截的。

回答by Travis J

If you have control of the server side which is hosting the page then you can handle this logically with a semaphore(wiki: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.

如果您可以控制托管页面的服务器端,那么您可以使用semaphore( wiki:semaphore)逻辑处理此问题。基本上它是一个旋转锁,将在他们的服务器端会话中实现。如果他们已进入但未以安全方式退出,则重置页面状态。自然地,与所有旋转锁一样,必须有一个安全状态来清除锁。