DEV Community

Cover image for Confirmation pop-up when exiting tab
Rahul
Rahul

Posted on • Edited on

6 1

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
  event.preventDefault(); 
  //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); 
Enter fullscreen mode Exit fullscreen mode

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⌛

Get weekly newsletter of amazing articles I posted this week and some offers or announcement. Subscribe from Here

Sentry blog image

How to reduce TTFB

In the past few years in the web dev world, we’ve seen a significant push towards rendering our websites on the server. Doing so is better for SEO and performs better on low-powered devices, but one thing we had to sacrifice is TTFB.

In this article, we’ll see how we can identify what makes our TTFB high so we can fix it.

Read more

Top comments (0)

SurveyJS custom survey software

JavaScript Form Builder UI Component

Generate dynamic JSON-driven forms directly in your JavaScript app (Angular, React, Vue.js, jQuery) with a fully customizable drag-and-drop form builder. Easily integrate with any backend system and retain full ownership over your data, with no user or form submission limits.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay