window.onbeforeunload在chrome中不起作用

sid*_*esh 4 onbeforeunload

这是我用于window.onbeforeunload的代码......

<head>
<script>

    window.onbeforeunload = func;

    function func() 
    {
        var request = new XMLHttpRequest();
        request.open("POST", "exit.php", true); 
        request.onreadystatechange = stateChanged;
        request.send(null);
    }
    function stateChanged()
    {
        if (request.readyState == 4 || request.readyState == "complete")
            alert("Succes!");
    }
    </script>
    </head>
Run Code Online (Sandbox Code Playgroud)

这适用于IE和mozila但不适用于镀铬.....请帮助......提前感谢.....

Lap*_*404 17

在最新版本的Chrome中,你唯一能用onbeforeunload做的就是设置警告信息.

window.onbeforeunload = function () {
    return "Are you sure";
};
Run Code Online (Sandbox Code Playgroud)

将工作.Chrome中忽略了函数中的其他代码


更新:从Chrome V51开始,将忽略返回的字符串并显示默认消息.

  • 今天仍然如此,Chrome版本为24.0.1312.57米.还请注意,您无法检查浏览器版本并向用户发送不同的消息...如果您放置`return',您确定";`在`if`语句中,Chrome也忽略了这一点. (3认同)

小智 11

知道我已经迟到了,但是为什么我的自定义beforeunload消息在Chrome中无法正常工作并且正在阅读此内容.因此,如果其他人也这样做,则从版本51开始的Chrome不再支持beforeunload上的自定义消息.显然,这是因为该功能被各种骗局滥用.相反,您会收到预定义的Chrome消息,该消息可能适合您的用途,也可能不适 更多详情:

https://developers.google.com/web/updates/2016/04/chrome-51-deprecations?hl=en#remove-custom-messages-in-onbeforeload-dialogs

个人认为他们所选择的消息并不是很好,因为它提到离开网站并且onbeforeunload最常见的合法用途之一是脏标记处理/检查网页表单所以它不是一个很好的措辞作为很多用户仍然在您的网站上的时间,只是错误地点击了取消或重新加载按钮.


Ric*_*ard 10

你应该试试这个:

window.onbeforeunload = function(e) {
  e.returnValue = 'onbeforeunload';
  return 'onbeforeunload';
};
Run Code Online (Sandbox Code Playgroud)

这适用于最新的 Chrome。我们有同样的问题e.returnValuewith valueonbeforeunload解决了我的问题。

你的代码应该是这样的:

    <head>
    <script>

    window.onbeforeunload = function(e) {
        e.returnValue = 'onbeforeunload';
        func();
        return ''onbeforeunload'';
    };

    function func() 
    {
        var request = new XMLHttpRequest();
        request.open("POST", "exit.php", true); 
        request.onreadystatechange = stateChanged;
        request.send(null);
    }
    function stateChanged()
    {
        if (request.readyState == 4 || request.readyState == "complete")
            alert("Succes!");
    }
    </script>
    </head>
Run Code Online (Sandbox Code Playgroud)


Bak*_*dan 1

尝试这个。我已经尝试过并且有效。有趣,但成功消息不像其他消息那样需要确认。

window.onbeforeunload = function() 
{
    if ( window.XMLHttpRequest )
    {
        console.log("before"); //alert("before");
        var request = new XMLHttpRequest();
        request.open("POST", "exit.php", true); 
        request.onreadystatechange = function () {
            if ( request.readyState == 4 && request.status == 200 )
            {
                console.log("Succes!"); //alert("Succes!");
            }
        };
        request.send();
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 你不能发出警报。由于 JavaScript 引擎不允许您执行任何阻塞脚本。 (2认同)