仅针对浏览器关闭事件

时间:2015-06-19 06:22:37

标签: javascript html

根据我现在正在工作的项目要求,我只需要在浏览器关闭时使用javascript向用户显示javascript警报。所有其他页面事件,如网址点击,按钮点击,F5键按等都将被忽略。我尝试过以下代码,但没有用。

var isPostBack = false;

$(function() {
    // You would copy this for select and any other form elements I forgot about

    $('input').live('click', function() { isPostBack = true; });
    $('a').live('click', function() { isPostBack = true; });

    document.onkeydown = function(e) { //attach to key down event to detect the F5 key
        isPostBack = false;

        if (!e) { //Firefox and Safari gets argument directly.
            e = window.event;
        }

        var key = e.keyCode ? e.keyCode : e.which;

        try {
            if (key == 116) { //F5 Key detected
                isPostBack = true;
            }
        }
        catch (ex) { }
    }
});

window.onbeforeunload = check;

function check() {
    if (!isPostBack) {
        // Do your unload code
        isPostBack = false;

        var strPath = window.location.pathname;

        if (strPath.indexOf('CustomerPortal') >= 0) {
            alert('Customer, you are leaving our page.');
        }
        else {
            alert('User, you are leaving our page.');
        }

        return "Are you sure you want to exit this page?";
    }
} 

请提供您宝贵的意见和帮助,以帮助实现我的目标要求。

0 个答案:

没有答案