Confirmation Before Closing of Tab/Browser using JavaScript

Today we’ll show you a small JavaScript snippet for displaying a confirmation dialog box at the time of closing the tab or browser. It is very helpful for both the user and website. For the better understanding of the uses of this script, we’re demonstrating two situations here.

Situation 1: In your web project an user fills up a long form but forgot to save the form and close the current tab or browser. In that case, he/she lose all the data and he/she would be very unhappy with your website.

Situation 2: Your website has a special offer or promotion for the visitors in a page. A visitor visits another page and left from the website without knowing those offers. You lose earning money.

When user closing tab/browser, if you implement a confirmation alert then it will help to solve the both the above-described situation. Not only for the above situations, you can use JavaScript browser close confirmation many other cases.

Using JavaScript onbeforeunload event, you can easily show a confirmation on tab close event. JavaScript onbeforeunload event display a message in a confirmation dialog box to inform the users whether they want to stay or leave the current page.

Place the below JavaScript code in 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>

Do you want to get implementation help, or enhance the functionality of this script? Click here to Submit Service Request

Leave a reply

keyboard_double_arrow_up