无法阻止刷新 window.onunload() 中的页面

Cannot prevent refreshing page in window.onunload()

本文关键字:onunload 刷新 window      更新时间:2023-09-26

我正在尝试显示提示消息,以防用户尝试刷新页面。我使用了window.onbeforeunload,它在其他浏览器上运行良好,但不能移动Safari。

我正在尝试使用Windows.onunload进行移动Safari,我可以显示提示消息,但无法阻止刷新页面。

下面是代码

<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;
            } 
        }
    }

我也尝试了页面隐藏事件,可以显示提示但仍然无法阻止刷新页面下面是代码

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

阅读此答案

为什么jQuery卸载在chrome和safari中不起作用?

在卸载之前,您不能有任何对话框/确认。

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

截至本网站的一些信息:

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

onbeforeunload和onunload在Safari中不起作用。所以我建议你尝试在野生动物园浏览器中使用页面隐藏事件。请尝试让我知道

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

试试这个

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