Page Life cycle - beforeunload, pagehide, unload

Have you ever wanted to save any data before the users closes the web page ?

There are JS events where we can send server side requests to save useful data . The normal synchronous http request does not work and only asynchronous methods like Fetch and sendBeacon API can be used.

beforeunload event

This event is typically used to alert a user that he is leaving the page and he needs to save any data if he would like to. The alert message displayed cannot be customized and looks like below.

In this event we can use sendBeacon to send any server request. However we will not be able to know if the user choose to stay or leave.

image.png

pagehide event

This event is called after the beforeunload event and is called when pageis closed or redirected to another page . This is a perfect candidate for using sendBeacon to send server side request for saving any state.

unload event

This event is called before the page is shut and all the resources are terminated. This is not a recommended place to send server request and has a higher percentage of failure .

<html>
<head>
<script type="text/javascript">
window.addEventListener("beforeunload", function (e){
e.preventDefault(); 
e.returnValue = '';
navigator.sendBeacon("http://localhost:3000/beforeunload", "text");
});

window.addEventListener("pagehide", function (e){
navigator.sendBeacon("http://localhost:3000/pagehide", "text");
});

window.addEventListener("unload", function(e){
navigator.sendBeacon("http://localhost:3000/unload", "text");
});

</script>
</head>

<body>

<input type="text">

</body>
</html>