窗口onbeforeunload事件有时有效,有时不起作用(chrome)

时间:2019-09-10 11:20:36

标签: javascript php jquery wordpress

我正在处理一个自定义脚本,该脚本的工作是检测选项卡/窗口是否关闭 然后执行wordpress功能。最初,它有效,但现在不起作用。

我已经在functions.php中创建了一个函数,并在脚本所在的地方创建了一个js文件。我要实现的目标是,当他/她关闭选项卡或浏览器窗口时,我想注销当前用户。

这是我的js代码:

window.onbeforeunload = function (event) {
    var message = 'Important: Please click on \'Save\' button to leave this page.';
    if (typeof event == 'undefined') {
        event = window.event;

    $.ajax({
        type: 'POST',
            url: ajaxurl,
            data: {
                'action':'add_myfunc',
            },
            success:function(data) {
                // This outputs the result of the ajax request
                //alert('data:'+data);
                console.log(data);
            },
            error: function(errorThrown){
                alert(errorThrown);
                console.log(errorThrown);
            }
        });
    }
    if (event) {
        event.returnValue = message;
    }
    return message;
};    

$(function () {
    $("a").click(function () {
        window.onbeforeunload = null;
    });
    $("input[type='button']").click(function () {
        window.onbeforeunload = null;
});
$("input[type='submit']").click(function () {
        window.onbeforeunload = null;
});
});

有时显示“离开/取消”提示,但有时不显示。如果有人可以帮助您,那就太好了。 预先感谢。

0 个答案:

没有答案