5

I have used window.onbeforeunload on my javascript codes, but apparently it only works for FireFox:

    <script type="text/javascript">
    window.onbeforeunload = function (e) {
       location.href="admin.jsp?action=logout";
    };
    </script>

I need this to close at least 5 renowned browsers (firefox,IE,opera,safari,and chrome). Can anyone help me out?

Doni Andri Cahyono
  • 793
  • 5
  • 16
  • 28

1 Answers1

7

Use a synchronous XHR to do this, and use the unload event instead of onbeforeunload:

window.addEventListener('unload', function() {
    var xhr = new XMLHttpRequest();
    xhr.open('GET', 'admin.jsp?action=logout', false);
    xhr.send(null);
}, false);
ThiefMaster
  • 310,957
  • 84
  • 592
  • 636
  • I don't know that all browsers will allow that. [See this question](http://stackoverflow.com/questions/7560532/what-can-i-put-in-beforeunload); I'm looking for more "real" documentation. – Pointy Dec 09 '12 at 01:06
  • I think it should work in all browsers. The unload shouldn't happen until the unload events have been finished - and the handler doesn't even return until the xhr has finished. – ThiefMaster Dec 09 '12 at 01:07
  • @ThiefMaster: Well, I tried your code but apparently it didn't really work as expected since when i look into database, the user is still there. But indeed, it updates the database when user re-login. It's different from my previous code, it really deletes from database completely. Any suggestion? – Doni Andri Cahyono Dec 09 '12 at 01:18