关闭窗口时的警告框,但不是重新加载 [英] alert box when closing window, but not on reload

查看:70
本文介绍了关闭窗口时的警告框,但不是重新加载的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm searching for a way to let my users know that they have to log off when they are closing the window. I've already founded this code:

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

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

This works perfectly when I close my page. just as I want, but it also shows when I reload the page, which shouldn't happen.

任何人都知道如何解决这个问题,是否可能?

Anyone an idea how to solve this, is it even possible?

推荐答案

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

I believe this will help solve your problem. It works by first detecting if the keycode 116 has been pressed by the user(f5 key) or in other words the refresh button. If it has it will store the state of this button press so that the event beforeunload will not display the prompt. Below is the javascript/jquery you will need:

注意:这在jsfiddle中不会按预期运行,所以我排除了一个例子。 / p>

Note: This will not behave as expected in a jsfiddle so I excluded an example.

//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

这篇关于关闭窗口时的警告框,但不是重新加载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆