关闭窗口时的警告框,但不是重新加载

我正在寻找一种方法让我的用户知道他们必须在关闭窗口时注销。 我已经创建了这段代码:

window.onbeforeunload = confirmExit; function confirmExit() { return "It is better if you log out, before you close this page!"; } $(function () { $("a").click(function() { window.onbeforeunload = null; }); }); 

当我关闭页面时,这非常有效。 就像我想要的那样,但它也显示我何时重新加载页面,这不应该发生。

任何人都知道如何解决这个问题,甚至可能吗?

我相信这有助于解决您的问题。 它的工作原理是首先检测用户是否按下了键码116(f5键),或者换句话说是刷新按钮。 如果有,它将存储此按钮的状态,以便事件beforeunload不会显示提示。 以下是您需要的javascript / jquery:

注意:这不会在jsfiddle中按预期运行,因此我排除了一个示例。

 //set the variable exit to true initially because you haven't hit //the f5 button yet to refresh var exit = true; //on keydown event to check if the f5 or 116 keycode has been pressed $(window).on("keydown",function(e){//begin window on keydown event //if the keycode = 116 //in other words the user has pressed the f5 key if(e.which === 116){//begin if then //set exit to false because so the prompt doesn't display exit = false; }//end if then });//end window on keydown event //bind the beforeunload event to the window $(window).bind("beforeunload", function() {//begin event //if exit = true then display the prompt if (exit === true) {//begin if then //display the prompt //note the browser may over ride the string in your return value return "Are you sure you want to leave?"; } else { //do nothing, no prompt will be created return; }//end if then });//end event