如何根据浏览器用户代理重定向页面?
我正在使用此脚本来检测用户代理标头中的字符串“safari”,然后将您重定向到“android.html”,如果用户代理标头不包含“safari”,我将如何更改代码以使其重定向?
var ua = navigator.userAgent.toLowerCase();
var isAndroid = ua.indexOf("safari") > -1; //&& ua.indexOf("mobile");
if(isAndroid) {
window.location = 'android.html';
}
编辑: 这是我修改后的代码。这有道理吗?它首先检测设备是否是 android,然后如果是 safari 浏览器则进行重定向。
var ua = navigator.userAgent.toLowerCase();
var isAndroid = ua.indexOf("android") > -1;
var isSafari = ua.indexOf("safari") == -1;
if(isAndroid) {
if(isSafari) {
window.location = 'android.html';
}
}
I am using this script to detect the string "safari" in the user agent header which then redirects you to "android.html" how would I change the code to make it so it redirects if the user agent header does NOT contain "safari"?
var ua = navigator.userAgent.toLowerCase();
var isAndroid = ua.indexOf("safari") > -1; //&& ua.indexOf("mobile");
if(isAndroid) {
window.location = 'android.html';
}
EDIT:
Here is my revised code. Does this make sense? It first detects whether the device is android or not then it redirects if it is a safari browser.
var ua = navigator.userAgent.toLowerCase();
var isAndroid = ua.indexOf("android") > -1;
var isSafari = ua.indexOf("safari") == -1;
if(isAndroid) {
if(isSafari) {
window.location = 'android.html';
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
只是为了使用变量的名称,将条件从
> 更改为-1
到== -1
。Just to go with the name of the variable, change the condition from
> -1
to== -1
.特定于浏览器的检测通常不是首选方法,因为使用功能检测通常更好。您考虑过现代化吗?
http://www.modernizr.com/
Browser specific detection is usually not the preferred approach as it's usually better to use feature detection. Have you thought about modernizr?
http://www.modernizr.com/