简体   繁体   中英

Cannot prevent refreshing page in window.onunload()

I'm trying to show a prompt message in case user trying to refresh the page. I used window.onbeforeunload and it's working fine on other browsers BUT not Mobile Safari.

I'm trying to use window.onunload for Mobile Safari, I can show the prompt message, but cannot prevent refreshing page.

Below is the code

<script>
    var iOS = ( navigator.userAgent.match(/(iPad|iPhone|iPod)/g) ? true : false );
    if(iOS){

        window.onunload = function() {
            var test = confirm("Are you sure you want to leave this page");

            if(!test){
                return false;
            } 

        }
    }

I also tried the pagehide event, can show the prompt but still cannot prevent refreshing page Below is the code

<script>

  window.addEventListener("pagehide", function(){
    var test = confirm("Are u sure you want to leave this page aaaaaaaaaaaaa");         
    if(!test){          
        return false;
    } 
  },false);

</script>

Read this answer

Why is jQuery unload not working in chrome and safari?

You cannot have any dialogs/confiems in beforeunload.

jQuery(window).on('beforeunload', function() {
  return 'Are you sure you want to leave this page';
});

As of some information from this site:

https://www.webkit.org/blog/516/webkit-page-cache-ii-the-unload-event/

onbeforeunload and onunload not working in safari. So I suggest you try using the pagehide event in the safari browser. Pls try and let me know

http://www.w3schools.com/jquerymobile/event_pagehide.asp

Try this

$(window).on('beforeunload', function() {
  return 'Your own message goes here...';
});

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