Anonymous
Anonymous

Reputation: 1094

Alert is not working when user try to refresh browser page using f5,ctrl+5 using jquery script

I have requirement of show alert to the user when user try to referesh tab in browser it should get alert "if you alert this page you will loose data" but I am using jquery for this still it is not working .

<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>

<script>
$(window).on('beforeunload', function(){ 
  alert("Don't refresh you will loose your all data?");   
  //or
  confirm("are you sure want to refresh this page !");
});
</script>

Upvotes: 4

Views: 1025

Answers (4)

user6299088
user6299088

Reputation:

Try This with return

Note: NOT all browsers support this

  $(window).on("beforeunload", function (event) {
    return "Are you sure you want to leave?";
  });
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>

Additional Info :

Google Chrome removed support for custom message in ver 51

Opera removed support for custom message in ver 38

Mozilla Firefox removed support for custom message in ver 44.0

Apple Safari removed support for custom message in ver 9.1

Ref : https://stackoverflow.com/a/38880926/6299088

Upvotes: 2

Himanshu Upadhyay
Himanshu Upadhyay

Reputation: 6565

Try this out:

<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>

<script>
$(document).mousedown(function(e){ 
    if( e.button == 2 ) { 
        window.location.reload();
        return false; 
    } 
    return true; 
});
$(window).on('keydown', function(e){
    e = e || window.event;
    if(e.keyCode == 116 || (event.key === "r" && event.ctrlKey)){
        alert("Don't refresh you will loose your all data?");
        confirm("are you sure want to refresh this page !");
    }
});
$(window).on('beforeunload', function(){ 
  alert("Don't refresh you will loose your all data?");   
  //or
  confirm("are you sure want to refresh this page !");
});
</script>

Upvotes: 0

Diwa
Diwa

Reputation: 73

Bind beforeunload event :

 $(window).bind("beforeunload",function(){ 
            return confirm("Do you want to refresh this page?");
    });

Upvotes: 0

Shailesh Kumar Kachhi
Shailesh Kumar Kachhi

Reputation: 149

It will be like this:

 $(window).on('beforeunload', function(){ 

    return confirm("are you sure want to refresh this page !");
  });

Upvotes: 1

Related Questions