在移动 Safari 中检测 iOS5(首选 JavaScript)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7814984/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 01:24:59  来源:igfitidea点击:

Detect iOS5 within mobile Safari (javascript preferred)

javascriptiphoneiosmobilesafari

提问by user969622

The new fixed positioning introduced in iOS5 corrupted my webapp and I need a way to detect iOS5 users.

iOS5 中引入的新固定定位损坏了我的 web 应用程序,我需要一种方法来检测 iOS5 用户。

How can I detect iOS5? What is the browser agent string? JavaScript preferred. Thanks!

如何检测iOS5?什么是浏览器代理字符串?首选 JavaScript。谢谢!

回答by chown

From the SO question: What is the iOS 5 user-agent string:

来自 SO 问题:What is the iOS 5 user-agent string

iPhone:

iPhone:

Mozilla/5.0 (iPhone; CPU iPhone OS 5_0 like Mac OS X) AppleWebKit/534.46 (KHTML, like Gecko) Version/5.1 Mobile/9A334 Safari/7534.48.3

Mozilla/5.0 (iPhone; CPU iPhone OS 5_0 like Mac OS X) AppleWebKit/534.46 (KHTML, like Gecko) Version/5.1 Mobile/9A334 Safari/7534.48.3

iPad:

iPad:

Mozilla/5.0 (iPad; CPU OS 5_0 like Mac OS X) AppleWebKit/534.46 (KHTML, like Gecko) Version/5.1 Mobile/9A334 Safari/7534.48.3

Mozilla/5.0 (iPad; CPU OS 5_0 like Mac OS X) AppleWebKit/534.46 (KHTML, like Gecko) Version/5.1 Mobile/9A334 Safari/7534.48.3

And here is way to test for ios 5.x in javascript:

这是在 javascript 中测试 ios 5.x 的方法:

<script type="text/javascript">
    if (navigator.userAgent.match(/OS 5(_\d)+ like Mac OS X/i))
        // this helps detect minor versions such as 5_0_1
        document.write("You have iOS 5! Aren't you special!");
</script>

回答by Pete Cook

I've developed chown's answer a bit further, with a check for any iOS5 device, be it 5 or 5.0.1 or any later versions:

我进一步开发了 chown 的答案,检查了任何 iOS5 设备,无论是 5 还是 5.0.1 或任何更高版本:

var ios5 = navigator.userAgent.match(/OS 5_[0-9_]+ like Mac OS X/i) != null;
if(ios5) {
    // Now you can do specific stuff for devices on any version of iOS5
}

回答by naderf

You need to account for "CPU OS 5_0" and "CPU iPhone OS 5_0", rough and dirty regex:

您需要考虑“CPU OS 5_0”和“CPU iPhone OS 5_0”,粗糙和肮脏的正则表达式:

<script type="text/javascript">
if (navigator.userAgent.match(/(iPad|iPhone);.*CPU.*OS 5_\d/i))
{ 
   alert("On iOS 5")
}
else
{
   alert("Not on iOS 5"); //could be either 4- or 6+
}
</script>

回答by Aaron

You could be using Modernizrand detecting for Web Workersas they were not available prior to iOS 5. You need to still exclude Android as Android 2.0+ has supported them. This will give you forward compatibility with iOS6 which you aren't going to get with either of the user agent parses already provided.

您可以使用Modernizr并检测Web Workers,因为它们在 iOS 5 之前不可用。您仍然需要排除 Android,因为 Android 2.0+ 已经支持它们。这将为您提供与 iOS6 的向前兼容性,而您将无法使用已提供的任何用户代理解析。