3

I want to make a HTTP POST (or even GET is fine) request when the user leave the page. I tried with 'onbeforeunload' 'unload' event listeners to watch when the users redirect to some other different page.

Is there any way I can check whether the user clicked on 'Leave' or 'Stay' button in default 'onbeforeunload' confirm box? I want to call the function (make a request) only when he clicks the 'Leave' button.

How can I achieve this?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Sagar Hani
  • 146
  • 2
  • 8
  • 5
    Possible duplicate of [JavaScript, browsers, window close - send an AJAX request or run a script on window closing](http://stackoverflow.com/questions/6162188/javascript-browsers-window-close-send-an-ajax-request-or-run-a-script-on-win) – Just a student May 10 '17 at 07:45
  • You only need to tap into the `unload` event which is fired only if user confirmed leaving during the `onbeforeunload` interaction. You must make the ajax call synchronous. See [this](http://stackoverflow.com/questions/1821625/ajax-request-with-jquery-on-page-unload). – hazardous May 10 '17 at 07:51

3 Answers3

1

you can try

window.onunload

the function depends on browser

There is both window.onbeforeunload and window.onunload, which are used differently depending on the browser.Quote from here

Community
  • 1
  • 1
Luke
  • 362
  • 1
  • 4
  • 13
1

onunload (or onbeforeunload) cannot redirect the user to another page. This is for security reasons.

If you want to show a prompt before the user leaves the page, use

onbeforeunload:

window.onbeforeunload = function(){
  return 'Are you sure you want to leave?';
};

Or with jQuery:

$(window).bind('beforeunload', function(){
  return 'Are you sure you want to leave?';
});

This will just ask the user if they want to leave the page or not, you cannot redirect them if they select to stay on the page. If they select to leave, the browser will go where they told it to go.

You can use onunload to do stuff before the page is unloaded, but you cannot redirect from there (Chrome 14+ blocks alerts inside onunload):

window.onunload = function() {
    alert('Bye.');
}

Or with jQuery:

$(window).unload(function(){
  alert('Bye.');
});
MySardar
  • 21
  • 4
0

Well, this is what I did :

  1. When user tries to leave the page - Call the API (which I wanted to call if user clicks on leave button) within onbeforeunload event listener.
  2. If user clicks on leave button, he will be redirected to other page.
  3. If user clicks on stay button, I have a timeout function inside onbeforeunload event listener which will be executed after certain amount of time (2 seconds) where user would stay on current page itself. [In this API I'm revoking the operations what was done by API which was called in 1st step]
Sagar Hani
  • 146
  • 2
  • 8