Confirmation pop-up when exiting tab

We're going to see how to implement a confirmation pop-up when a user tries to leave the page which has an unsaved state or something processing in the background.

The beforeunload event is fired when the window, the document and its resources are about to be unloaded. The document is still visible and the event is still cancelable at this point. This event enables a web page to trigger a confirmation dialogue asking the user if they want to leave the page. If the user confirms, the browser navigates to the new page, otherwise, it cancels the navigation.

Let's see how to do it...

When your webpage is doing something in the background or it has some data which is not sent to the server yet you can set up the event listener and how the user a confirmation pop-up if he tries to close or reload the tab.

 function setConfirmation(event) {
  // Cancel the event as stated by the standard
  //Chrome requires returnValue to be set. 
  event.returnValue = ''; 
 window.addEventListener('beforeunload;, setconfirmation); 
 // When everything is done just remove the event listener to allow the user to leave the page without confirmation
 window.removeEventListener('beforeunload;, setConfirmation);

To combat unwanted pop-ups, some browsers don't display prompts created in beforeunload event handlers unless the page has been interacted with. Moreover, some don't display them at all.

This was it just a small post ��

🥂Thanks For Reading | Happy Coding⌛

No Comments Yet