In this blog, we’ll explain to you a small JavaScript snippet for showcasing a confirmation dialog box at the time of closing the tab/browser. It is beneficial for both the user and the website. To understand this script correctly, here we take two situations.
Situation 1: In your web project, suppose a user fills up a long-form, but he/she forgot to save the form and then close the browser or tab. In this case, he/she lose all the data, and he/she would not satisfy with your website.
Situation 2: Your website has an extraordinary offer or promotion for the visitors on a page. A visitor visits another page and left from the site without knowing those offers. You lose earning money.
When the user closes the tab/browser, if you implement a confirmation alert, then it will help to solve both the above-described situation. Not only for the above circumstances, but you can also use JavaScript browser close confirmation for many other cases.
With the use of JavaScript onbeforeunload event, you can easily show confirmation on tab close event. JavaScript onbeforeunload event displays a message in a confirmation dialog box to inform the users whether they want to stay or leave the page.
Place the below JavaScript code on the desired webpage. Only change the confMessage variable value as per the suitable message which you want to show to the user.
<script type="text/javascript"> var areYouReallySure = false; function areYouSure() { if(allowPrompt){ if (!areYouReallySure && true) { areYouReallySure = true; var confMessage = "***************************************\n\n W A I T !!! \n\nBefore leaving our site, follow CodexWorld for getting regular updates on Programming and Web Development.\n\n\nCLICK THE *CANCEL* BUTTON RIGHT NOW\n\n***************************************"; return confMessage; } }else{ allowPrompt = true; } } var allowPrompt = true; window.onbeforeunload = areYouSure; </script>
Also, read our previous blog- Build an HTML5 Video Player with Custom Controls