0

I have to call a webservice using AJAX before browser gets closed. So to get the browser close event I am using the following javascript code

window.onbeforeunload = function(e) {
    alert("Browser close event test");
    e = e || window.event;
    e.preventDefault = true;
    e.cancelBubble = true;
    e.returnValue = 'test';

    //write your code here
}

Somehow it is only working in IE and not in Chrome and Firefox. Don't know why? You can check this fiddle in different browser https://jsfiddle.net/yFuPr/2149/

I have referred this post Crossbrowser onbeforeunload?

but for him it is not even working in IE. I have other problem, the code is only working in IE.

halfer
  • 19,824
  • 17
  • 99
  • 186
Nikhil Agrawal
  • 26,128
  • 21
  • 90
  • 126
  • Isn't Mozilla and Firefox the same? or was that just a typo and you meant to say Chrome as well? – Curious13 Jan 17 '18 at 17:05
  • @Curious13 Sorry, I will correct. Thanks. – Nikhil Agrawal Jan 17 '18 at 17:06
  • It is not going to fire the alert and there is no way to cancel the event. You can not prevent us to stay there. If the person wants to leave, the browser allows it. – epascarello Jan 17 '18 at 17:11
  • @epascarello if we remove those statements from the above code, Is it possible to call a webservice from there? – Nikhil Agrawal Jan 17 '18 at 17:14
  • You can, but it is a race condition because the browser kills open http requests. – epascarello Jan 17 '18 at 17:32
  • @epascarello Sorry but didn't understood. Can you brief little bit? – Nikhil Agrawal Jan 17 '18 at 17:44
  • You make a call to the server, chrome kills the open requests.... So you have to hope your call makes it before chrome kills it. There is not guaranteed way to make a call to the server. And if the browser crashes, your call will not go out. – epascarello Jan 17 '18 at 17:46
  • I've tidied up this post to fix some case errors. In addition, I notice you are adding please-help-me messages to a lot of your questions; you may not be aware that it's quite clear you'd like some help, and that to English speakers, this addition may read rather like a form of begging. Accordingly, it is the sort of thing volunteers tend to trim out, so if you can refrain from adding this to _everything_ you post, you'd be saving them from some additional work. Thanks! – halfer Jan 18 '18 at 00:23

0 Answers0