1

Is there any way to show popup when close the browser tab? In popup there should be a button to see more and when user clicks that button user should be redirected to the see more page. If user click cancel button in the popup user will leave the website. Is there any possible way to do this? I currently try this code. It shows the popup but it suddenly dis-sappers. I think condition also not working.

    var userclicked=false;
    window.onbeforeunload = function(e) {
        //e.preventDefault();
        if(!document.hasfocus()){

        Swal.fire({
            title: 'New Promotions!',
            text: 'Visit to See New Promotions!',
            type: 'info',
            showCancelButton: true,
            confirmButtonText: 'View More',
            cancelButtonText: 'Cancel',
            showCloseButton: true
        }).then((result) => {
            if (result.value) {  userclicked=true;
                window.location = "{{url('front/promotionpage')}}";                
            } else if (result.dismiss === Swal.DismissReason.cancel) {    userclicked=true;            
            }
        });            

        if(userclicked){
            return "Hi";
        }else{
            return null;
        }
        }

        //return "hi";

        //window.onbeforeunload = null;
        //return null;
        //return "Hi";
    }

2 Answers2

1

You can add this simple code. It shows an alert when you want to close browsers window.

window.onbeforeunload = function() {
    var message = 'Do you want to leave this page?';
    return message;
}
Moshiur Rahman
  • 1,534
  • 12
  • 26
  • 2
    Note that the `message` text will be completely ignored in most browsers. – Rory McCrossan Oct 30 '19 at 10:29
  • Thanks Moshiur, But the message in the variable set not rendering on close event, it showing predefined message "Changes you made on site may not be saved". is there any way we can show customized message or popup in beforeunload event? – Mitul Jul 12 '22 at 07:12
  • as far as I know, Custom messages are not showing in updated browsers. – Moshiur Rahman Jul 17 '22 at 06:26
1

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. DOC

 window.addEventListener('beforeunload', (event) => {
      // Cancel the event as stated by the standard.
      event.preventDefault();
      // Chrome requires returnValue to be set.
      event.returnValue = '';
    });
Saurabh Yadav
  • 3,303
  • 1
  • 10
  • 20