window.onbeforeunload 不适用于 iPad? [英] window.onbeforeunload not working on the iPad?

查看:45
本文介绍了window.onbeforeunload 不适用于 iPad?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有谁知道 iPad 是否支持 onbeforeunload 事件和/或是否有不同的使用方式?

Does anyone know if the onbeforeunload event is supported on the iPad and/or if there's a different way to use it?

我已经尝试了几乎所有的方法,似乎 onbeforeunload 事件从未在 iPad(Safari 浏览器)上触发.

I've tried pretty much everything, and it seems like the onbeforeunload event is never triggered on the iPad (Safari browser).

具体来说,这是我尝试过的:

Specifically, this is what I've tried:

  • window.onbeforeunload = function(event) { event.returnValue = 'test';}
  • window.onbeforeunload = function(event) { return 'test';}
  • (以上两个一起)
  • window.onbeforeunload = function(event) { alert('test')';}
  • (上述所有函数,但在

所有这些都适用于 PC 上的 FF 和 Safari,但不适用于 iPad.

All of these work on FF and Safari on the PC, but not on the iPad.

此外,我在加载页面后刚刚完成了以下操作:

Also, I've done the following just after loading the page:

alert('onbeforeunload' in window);
alert(typeof window.onbeforeunload);
alert(window.onbeforeunload);

分别是:

  • true
  • 对象
  • null

因此,浏览器确实具有该属性,但由于某种原因它没有被触发.

So, the browser does have the property, but for some reason it doesn't get fired.

我尝试离开页面的方法是单击后退和前进按钮、在顶部栏中进行谷歌搜索、更改地址栏中的位置以及单击书签.

The ways I try to navigate away from the page are by clicking the back and forward buttons, by doing a google search in the top bar, by changing location in the address bar, and by clicking on a bookmark.

有人知道发生了什么吗?我将不胜感激任何输入.

Does anyone have any idea about what's going on? I'd greatly appreciate any input.

谢谢

推荐答案

这段 JavaScript 代码适用于 ipad 和 iphone 上的 Safari 和 Chrome,以及台式机/笔记本电脑/其他浏览器:

This bit of JavaScript works for me on Safari and Chrome on ipad and iphone, as well as desktop/laptop/other browsers:

var isOnIOS = navigator.userAgent.match(/iPad/i)|| navigator.userAgent.match(/iPhone/i);
var eventName = isOnIOS ? "pagehide" : "beforeunload";

window.addEventListener(eventName, function (event) { 
    window.event.cancelBubble = true; // Don't know if this works on iOS but it might!
    ...
} );

这篇关于window.onbeforeunload 不适用于 iPad?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆