如何根据浏览器用户代理重定向页面?

发布于 2025-01-01 22:08:52 字数 665 浏览 3 评论 0原文

我正在使用此脚本来检测用户代理标头中的字符串“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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

爱她像谁 2025-01-08 22:08:52
if(!isAndroid) {
window.location = 'android.html';
}
if(!isAndroid) {
window.location = 'android.html';
}
梦中的蝴蝶 2025-01-08 22:08:52

只是为了使用变量的名称,将条件从 > 更改为-1== -1

var isAndroid = ua.indexOf("safari") == -1;
if(isAndroid) {
   window.location = 'android.html';
}

Just to go with the name of the variable, change the condition from > -1 to == -1.

var isAndroid = ua.indexOf("safari") == -1;
if(isAndroid) {
   window.location = 'android.html';
}
一生独一 2025-01-08 22:08:52

特定于浏览器的检测通常不是首选方法,因为使用功能检测通常更好。您考虑过现代化吗?
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/

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文