简体   繁体   中英

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>

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

It will be like this:

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

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

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>

Bind beforeunload event :

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM