window.onbeforeunload in Chrome: what is the most recent fix?

家住魔仙堡 提交于 2019-12-17 06:41:39

问题


Obviously, window.onbeforeunload has encountered its fair share of problems with Chrome as I've seen from all the problems I've encountered. What's the most recent work around?

The only thing I've got even close to working is this:

window.onbeforeunload = function () { return "alert" };

However, if I substitute return "alert" with something like alert("blah"), I get nothing from Chrome.

I saw in this question that Google purposefully blocks this. Good for them... but what if I want to make an AJAX call when someone closes the window? In my case, I want to know when someone has left the chatroom on my website, signalled by the window closing.

I want to know if there's a way to either
(a): fix the window.onbeforeunload call so that I can put AJAX in there
or
(b): get some other way of determining that a window has closed in Chrome


回答1:


Answer:

$(window).on('beforeunload', function() {
    var x =logout();
    return x;
});
function logout(){
        jQuery.ajax({
        });
        return 1+3;
}

A little mix and match, but it worked for me. The 1+3 makes sure that the logout function is being called (you'll see 4 if it's successful on the popup when you try to leave).




回答2:


Here's a more straightforward approach.

$(window).on('beforeunload', function() {
    return "You should keep this page open.";
});

The returned message can be anything you want, including the empty string if you have nothing to add to the message that Chrome already shows. The result looks like this:




回答3:


According to MDN,

The function should assign a string value to the returnValue property of the Event object and return the same string.

This is the following

window.addEventListener( 'beforeunload', function(ev) { 
    return ev.returnValue = 'My reason';
})



回答4:


As of 69.0.3497.92, Chrome has not met the standard. However, there is a bug report filed, and a review is in progress.

  • Chrome requires returnValue to be set by reference to the event object, not the value returned by the handler.
  • The standard states that prompting can be controlled by canceling the event or setting the return value to a non-null value.
  • The standard states that authors should use Event.preventDefault() instead of returnValue.
  • The standard states that the message shown to the user is not customizable.

window.addEventListener('beforeunload', function (e) {
    // Cancel the event as stated by the standard.
    e.preventDefault();
    // Chrome requires returnValue to be set.
    e.returnValue = '';
});
    
window.location = 'about:blank';


来源:https://stackoverflow.com/questions/9626059/window-onbeforeunload-in-chrome-what-is-the-most-recent-fix

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!