JavaScript, browsers, window close - send an AJAX request or run a script on window closing
Asked Answered
L

10

65

I'm trying to find out when a user left a specified page. There is no problem finding out when he used a link inside the page to navigate away but I kind of need to mark up something like when he closed the window or typed another URL and pressed enter. The second one is not so important but the first one is. So here is the question:

How can I see when a user closed my page (capture window.close event), and then... doesn't really matter (I need to send an AJAX request, but if I can get it to run an alert, I can do the rest).

Lowestoft answered 28/5, 2011 at 14:19 Comment(0)
D
53

There are unload and beforeunload javascript events, but these are not reliable for an Ajax request (it is not guaranteed that a request initiated in one of these events will reach the server).

Therefore, doing this is highly not recommended, and you should look for an alternative.

If you definitely need this, consider a "ping"-style solution. Send a request every minute basically telling the server "I'm still here". Then, if the server doesn't receive such a request for more than two minutes (you have to take into account latencies etc.), you consider the client offline.


Another solution would be to use unload or beforeunload to do a Sjax request (Synchronous JavaScript And XML), but this is completely not recommended. Doing this will basically freeze the user's browser until the request is complete, which they will not like (even if the request takes little time).

Drover answered 28/5, 2011 at 14:31 Comment(10)
Well if he is doing a logout then I have seen working examples where the unload opens a popup windows that then logs the user out (doe this solve the non guarentee issue?).Sassan
No. I bet there are popup blockers out there that do not allow popups on those events. Also, it's terrible UX to open a popup when the user closes the tab/window.Drover
I assume the issue is that the request takes time and the browser might be finished with unload by the time it is finished (so it just might never finish)?Sassan
I am actually doing the I am still here thing. But is kind of slow and reduce user experience. Also reducing the interval of the "i'm still here" can kill the server at a high rate of users. So I was trying to replace it with something else. When you say the request is not reliable how unreliable u mean? I can use that and double it with sending messages at a higher interval is has more than 50% rate of success. I think that can improve performance on both sides (server and client).Lowestoft
Basically, yes. When closing a tab/window the browser usually clears everything related to it, which often means cancelling any AJAX requests.Drover
Well then you might want to look into the opening a simple small popup that then logs you out. I agree with Felix, it did not work perfectly but most popup blockers allow you to set exceptions easily and overall it works pretty well when I used it. It is not a perfect solution, but then nothing ever is. note: You will want to store the code for the popup with the mother page and not send a request for it from the server or you will just encounter the same problem.Sassan
To answer the % of success, I imagine it would be totally dependant on the spend of the request (so internet/computer speed/server speed might all come into play).Sassan
Ok... how about this. Would the "closing" stop if I use a prompt? Some thing like onUnload/beforUnload use a prompt with "are u sure u want to leave?" This should give the page suficient time to send the request... Or if not I can make a pop up like u suggested and mime a prompt in it.Lowestoft
I think it would be your best bet (although you'd still have to do the pinging if you want to be 100% sure). BTW, the way to do this is to return "a string"; in your beforeunload handler (doing a confirm() won't work).Drover
2018 update: beacon API landed in browsers and solves this problem. See this answer : https://mcmap.net/q/67656/-javascript-browsers-window-close-send-an-ajax-request-or-run-a-script-on-window-closingHurlburt
H
96

Updated 2024

Beacon API is the solution to this issue in all modern browsers.

A beacon request is supposed to complete even if the user exits the page.

If you are looking to catch a user exit, visibilitychange (not unload) is the last event reliably observable in modern browers and is well supported now.

<script>
  document.addEventListener('visibilitychange', function() {

    if (document.visibilityState === "hidden") {
      var url = "https://example.com/foo";
      var data = "bar";

      navigator.sendBeacon(url, data);
    }
  });
</script>

If you need to support old browsers, you can use the lifecycle.js library.

Details

Beacon requests are supposed to run to completion even if the user leaves the page - switches to another app, etc - without blocking user workflow.

Under the hood, it sends a POST request along with the user credentials (cookies), subject to CORS restrictions.

    var url = "https://example.com/foo";
    var data = "bar";

    navigator.sendBeacon(url, data);

The question is when to send your Beacon request. Especially if you want to wait until the last moment to send session info, app state, analytics, etc.

It used to be common practice to send it during the unload event, but changes to page lifecycle management - driven by mobile UX - killed this approach. Today, most mobile workflows (switching to new tab, switching to the homescreen, switching to another app...) do not trigger the unload event.

If you want to do things when a user exits your app/page, it is now recommended to use the visibilitychange event and check for transitioning from passive to hidden state.

document.addEventListener('visibilitychange', function() {
      
  if (document.visibilityState == 'hidden') {
    
     // send beacon request
  }

});

The transition to hidden is often the last state change that's reliably observable by developers (this is especially true on mobile, as users can close tabs or the browser app itself, and the beforeunload, pagehide, and unload events are not fired in those cases).

This means you should treat the hidden state as the likely end to the user's session. In other words, persist any unsaved application state and send any unsent analytics data.

Details of the Page lifecyle API are explained in this article.

In 2024, implementation of the visibilitychange event is consistent across modern browsers.

If you need to support old broswers, using the lifecycle.js library and page lifecycle best practices seems like a good solution.

# lifecycle.js (1K) for cross-browser compatibility
# https://github.com/GoogleChromeLabs/page-lifecycle

<script defer src="/path/to/lifecycle.js"></script>
<script defer>
lifecycle.addEventListener('statechange', function(event) {

  if (event.originalEvent == 'visibilitychange' && event.newState == 'hidden') {
    var url = "https://example.com/foo";
    var data = "bar";

    navigator.sendBeacon(url, data);
  }
});
</script>

For more numbers about the reliability of vanilla page lifecycle events (without lifecycle.js), there is also this study, but it's a bit old now.

Adblockers

Adblockers seem to have options that block sendBeacon requests.

Cross site requests

Beacon requests are POST requests that include cookies and are subject to CORS spec. More info.

Hurlburt answered 24/2, 2018 at 8:47 Comment(11)
This answer changed my life! Thanks a lot!Eglanteen
MDN says unload and beforeunload aren’t the right events to use with sendBeacon. Instead, use visibilitychange so this is useless developer.mozilla.org/en-US/docs/Web/API/Navigator/sendBeaconDorkas
@Dorkas Indeed. MDN reverted their recommendation for using unload recently : github.com/mdn/sprints/issues/3722 . I have rewritten the answer to take this into account.Hurlburt
@AlfieRobles please check the changes to this answer if you are relying on the unload event for important data.Hurlburt
This looks promising but it seems we can't set request headers with Beacon requests? The MDN page for sendBeacon doesn't mention them but I found this article which notes that only Content-Type is possible. Am I wrong on this or will this likely require the receiving API to be updated so as to allow bypassing things like authentication (or handling them via the request payload rather than headers)?Supernational
I'm also wondering if keep-alive, suggested by that article, would play a useful role here at all.Supernational
Note: Adblock seems to block most of the calls made using navigator.sendBeacon();Pestalozzi
@GregVenech About keep-alive, your link mentions : "Connection-specific header fields such as Connection and Keep-Alive are prohibited in HTTP/2. Chrome and Firefox ignore them in HTTP/2 responses, Safari does not load any response that contains them."Hurlburt
@GregVenech About authentication, my understanding is that sendBeacon, which makes sense as a background event, will embark cookies like other requests, enabling your app to identify the userHurlburt
@BharadwajGiridhar can you point to info on that ? I have found this for adblockplus. Is that it ?Hurlburt
@Hurlburt don't have a link, but I tested with the same adblockplus.org plugin on Edge (Based on Chromium) and saw by navigator.sendBeacon() calls being blocked. In my use case, I run crewcharge.com where my script (like google analytics) needs to be embedded onto another site. Maybe adblock just blocks navigator.sendBeacons () from cross-origin sites. Please test accordingly.Pestalozzi
D
53

There are unload and beforeunload javascript events, but these are not reliable for an Ajax request (it is not guaranteed that a request initiated in one of these events will reach the server).

Therefore, doing this is highly not recommended, and you should look for an alternative.

If you definitely need this, consider a "ping"-style solution. Send a request every minute basically telling the server "I'm still here". Then, if the server doesn't receive such a request for more than two minutes (you have to take into account latencies etc.), you consider the client offline.


Another solution would be to use unload or beforeunload to do a Sjax request (Synchronous JavaScript And XML), but this is completely not recommended. Doing this will basically freeze the user's browser until the request is complete, which they will not like (even if the request takes little time).

Drover answered 28/5, 2011 at 14:31 Comment(10)
Well if he is doing a logout then I have seen working examples where the unload opens a popup windows that then logs the user out (doe this solve the non guarentee issue?).Sassan
No. I bet there are popup blockers out there that do not allow popups on those events. Also, it's terrible UX to open a popup when the user closes the tab/window.Drover
I assume the issue is that the request takes time and the browser might be finished with unload by the time it is finished (so it just might never finish)?Sassan
I am actually doing the I am still here thing. But is kind of slow and reduce user experience. Also reducing the interval of the "i'm still here" can kill the server at a high rate of users. So I was trying to replace it with something else. When you say the request is not reliable how unreliable u mean? I can use that and double it with sending messages at a higher interval is has more than 50% rate of success. I think that can improve performance on both sides (server and client).Lowestoft
Basically, yes. When closing a tab/window the browser usually clears everything related to it, which often means cancelling any AJAX requests.Drover
Well then you might want to look into the opening a simple small popup that then logs you out. I agree with Felix, it did not work perfectly but most popup blockers allow you to set exceptions easily and overall it works pretty well when I used it. It is not a perfect solution, but then nothing ever is. note: You will want to store the code for the popup with the mother page and not send a request for it from the server or you will just encounter the same problem.Sassan
To answer the % of success, I imagine it would be totally dependant on the spend of the request (so internet/computer speed/server speed might all come into play).Sassan
Ok... how about this. Would the "closing" stop if I use a prompt? Some thing like onUnload/beforUnload use a prompt with "are u sure u want to leave?" This should give the page suficient time to send the request... Or if not I can make a pop up like u suggested and mime a prompt in it.Lowestoft
I think it would be your best bet (although you'd still have to do the pinging if you want to be 100% sure). BTW, the way to do this is to return "a string"; in your beforeunload handler (doing a confirm() won't work).Drover
2018 update: beacon API landed in browsers and solves this problem. See this answer : https://mcmap.net/q/67656/-javascript-browsers-window-close-send-an-ajax-request-or-run-a-script-on-window-closingHurlburt
V
40

1) If you're looking for a way to work in all browsers, then the safest way is to send a synchronous AJAX to the server. It is is not a good method, but at least make sure that you are not sending too much of data to the server, and the server is fast.

2) You can also use an asynchronous AJAX request, and use ignore_user_abort function on the server (if you're using PHP). However ignore_user_abort depends a lot on server configuration. Make sure you test it well.

3) For modern browsers you should not send an AJAX request. You should use the new navigator.sendBeacon method to send data to the server asynchronously, and without blocking the loading of the next page. Since you're wanting to send data to server before user moves out of the page, you can use this method in a unload event handler.

$(window).on('unload', function() {
    var fd = new FormData();
    fd.append('ajax_data', 22);
    navigator.sendBeacon('ajax.php', fd);
});

There also seems to be a polyfill for sendBeacon. It resorts to sending a synchronous AJAX if method is not natively available.

IMPORTANT FOR MOBILE DEVICES : Please note that unload event handler is not guaranteed to be fired for mobiles. But the visibilitychange event is guaranteed to be fired. So for mobile devices, your data collection code may need a bit of tweaking.

You may refer to my blog article for the code implementation of all the 3 ways.

Vinnievinnitsa answered 4/11, 2017 at 6:52 Comment(2)
In 2018, this is the best response. Use the beacon API. Read the blog article mentionned in the answer ( usefulangle.com/post/62/… ) for more details.Hurlburt
I knew it existed but couldn't remember it's name. This is the correct answer IMO "navigator.sendBeacon" <--Denna
L
4

Years after posting the question I made a way better implementation including nodejs and socket.io (https://socket.io) (you can use any kind of socket for that matter but that was my personal choice).

Basically I open up a connection with the client, and when it hangs up I just save data / do whatever I need. Obviously this cannot be use to show anything / redirect the client (since you are doing it server side), but is what I actually needed back then.

 io.on('connection', function(socket){
      socket.on('disconnect', function(){
          // Do stuff here
      });
 });

So... nowadays I think this would be a better (although harder to implement because you need node, socket, etc., but is not that hard; should take like 30 min or so if you do it first time) approach than the unload version.

Lowestoft answered 5/9, 2019 at 18:4 Comment(0)
S
3

I also wanted to achieve the same functionality & came across this answer from Felix(it is not guaranteed that a request initiated in one of these events will reach the server).

To make the request reach to the server we tried below code:-

onbeforeunload = function() {

    //Your code goes here.

    return "";
} 

We are using IE browser & now when user closes the browser then he gets the confirmation dialogue because of return ""; & waits for user's confirmation & this waiting time makes the request to reach the server.

Sanyu answered 24/2, 2015 at 11:25 Comment(1)
it seems current Chrome ignores this at all if there is more than only retrun string statement in beforeunload function. So you can do return "Do you want to close?", but you cannot do anything else…Bodoni
S
1

The selected answer is correct that you can't guarantee that the browser sends the xhr request, but depending on the browser, you can reliably send a request on tab or window close.

Normally, the browser closes before xhr.send() actually executes. Chrome and edge look like they wait for the javascript event loop to empty before closing the window. They also fire the xhr request in a different thread than the javascript event loop. This means that if you can keep the event loop full for long enough, the xhr will successfully fire. For example, I tested sending an xhr request, then counting to 100,000,000. This worked very consistently in both chrome and edge for me. If you're using angularjs, wrapping your call to $http in $apply accomplishes the same thing.

IE seems to be a little different. I don't think IE waits for the event loop to empty, or even for the current stack frame to empty. While it will occasionally correctly send a request, what seems to happen far more often (80%-90% of the time) is that IE will close the window or tab before the xhr request has completely executed, which result in only a partial message being sent. Basically the server receives a post request, but there's no body.

For posterity, here's the code I used attached as the window.onbeforeunload listener function:

  var xhr = new XMLHttpRequest();
  xhr.open("POST", <your url here>);
  xhr.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
  var payload = {id: "123456789"};
  xhr.send(JSON.stringify(payload));

  for(var i = 0; i < 100000000; i++) {}

I tested in:

Chrome 61.0.3163.100

IE 11.608.15063.0CO

Edge 40.15063.0.0

Such answered 25/10, 2017 at 23:14 Comment(1)
The time spent on your for loop will vary based on CPU, JS Engine and other factors. A slightly less bad idea would be to block the event loop for 100ms or any other value that is deemed long enough after experimentingSenseless
A
0

Try this one. I solved this problem in javascript, sending ajax call to server on browse or tab closing. I had a problem with refreshing page because on onbeforeunload function including refreshing of the page. performance.navigation.type == 1 should isolate refresh from closing (on mozzila browser).

$(window).bind('mouseover', (function () { // detecting DOM elements
    window.onbeforeunload = null;
}));

$(window).bind('mouseout', (function () { //Detecting event out of DOM
      window.onbeforeunload = ConfirmLeave;
}));

function ConfirmLeave() {
   if (performance.navigation.type == 1) { //detecting refresh page(doesnt work on every browser)
   }
   else {
       logOutUser();
   }
}

$(document).bind('keydown', function (e) { //detecting alt+F4 closing
    if (e.altKey && e.keyCode == 115) {
        logOutUser();
    }    
});
function logOutUser() {
   $.ajax({
     type: "POST",
     url: GWA("LogIn/ForcedClosing"), //example controller/method
     async: false
   });
}
Aprilette answered 5/9, 2019 at 14:46 Comment(2)
Hello and welcome to SO. Not downvoting (since you are new :) ) but your answer brings nothing new to the accepted answer. Also if I am reading it correctly it triggers the ConfirmLeave function everytime user moves mouse outside the window, resulting in fake requests (for example each time he moves mouse over task bar or something). Also it doesn't treat any kind of touch / mobile cases (since event is bound only on mouseOut, removed on over, and never bound back). Also consider the case of simply pressing f5 (not working either in your example).Lowestoft
In 2011 (when I posted the question) it was not possible (or at least not so simple as today), but nowadays you can use a websocket for this, which basically brings you the advantages of the ping style solution without their drawbacks. If you wanna check something about that I would gladly upvote an answer like it (I was considering posting one myself but... got lazy :) ).Lowestoft
M
0
$(window).on('beforeunload', function() {


// This function is triggered when the user is about to leave the page (beforeunload event).

let requestData = {
    action: "immediate_sent_abandon_email",
    // attached some data
};
// An object 'requestData' is created to hold data, and an 'action' property is set to "immediate_sent_abandon_email".

// Convert the data to a URL-encoded string
let requestDataString = Object.keys(requestData).map(key => {
    return encodeURIComponent(key) + '=' + encodeURIComponent(requestData[key]);
}).join('&');
// The data in 'requestData' is converted to a URL-encoded string. Each key-value pair is encoded, and the pairs are joined with '&'.

// Use navigator.sendBeacon to send a POST request
navigator.sendBeacon(frontend_ajax_object.ajaxurl, new Blob([requestDataString], { type: 'application/x-www-form-urlencoded' }));
// navigator.sendBeacon is used to send a POST request. 'frontend_ajax_object.ajaxurl' is the URL to which the request is sent.
// The data is passed as a Blob (Binary Large Object), specifying the type as 'application/x-www-form-urlencoded'.
});
Meave answered 18/12, 2023 at 12:38 Comment(0)
P
-1

Im agree with Felix idea and I have solved my problem with that solution and now I wanna to clear the Server Side solution:

1.send a request from client side to server

2.save time of the last request recived in a variable

3.check the server time and compare it by the variable of last recived request

4.if the result is more than the time you expect,start running the code you want to run when windows closed...

Pandorapandour answered 8/3, 2014 at 10:17 Comment(0)
S
-5

Use:

<body onUnload="javascript:">

It should capture everything except shutting down the browser program.

Sassan answered 28/5, 2011 at 14:25 Comment(2)
hmm (-1), I would be very interested to know what is wrong with this method. Never used it myself but have encountered it many times as the solution to your exact problem.Sassan
I have posted an answer in which I explain the -1.Drover

© 2022 - 2024 — McMap. All rights reserved.