Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
468 views
in Technique[技术] by (71.8m points)

javascript - window.onbeforeunload and window.onunload is not working in Firefox, Safari, Opera?

In my chat application I need to get confirmation from user, when my application closes.

So I used the window.onbeforeunload for confirmation alert and window.onunload for logout().

  1. But both functions are working in IE and Chrome. (Application works fine)

  2. window.onbeforeunload not working in Opera and my message will not get displayed in Firefox.

  3. window.onunload not working in Safari, Opera and Firefox.

My JavaScript code will be:

// Used for confirmation, to closing the window 
window.onbeforeunload = function () {

    return  "Are you sure want to LOGOUT the session ?";
}; 

// Used to logout the session, when browser window was closed 
window.onunload = function () {

    if((sessionId != null)&&(sessionId!="null")&& (sessionId != ""))
        logout();
};

I also tried the same function with JQuery,

<script type="text/javascript">

    $(window).on('beforeunload', function() {
        return 'Are you sure want to LOGOUT the session ?';
    });

    $(window).unload(function() {
        if ((sessionId != null) && (sessionId != "null") && (sessionId != "")) {
            logout();
        }
    });
    
</script>
Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Unfortunately, the methods you are using are unsupported in those browsers. To support my answer (this unsupportive behaviour) I have given links below.

onbeforeunload and onunload not working in opera... to support this

onbeforeunload in Opera
http://www.zachleat.com/web/dont-let-the-door-hit-you-onunload-and-onbeforeunload/

Though the onunload event doesn't work completely, you can use onunload to show a warning if a user clicks a link to navigate away from a page with an unsaved form.

onunload not working in safari... to support this

https://www.webkit.org/blog/516/webkit-page-cache-ii-the-unload-event/

You could rather try using the pagehide event in the safari browser in lieu of onunload.

onunload not working in firefox... to support this

https://bugzilla.mozilla.org/show_bug.cgi?id=681636

They are yet to come up with a solution in FF too

Wish you good luck cheers.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...