安卓模拟器浏览器检测

7
我正在开发一个网站的移动版,目前使用以下JavaScript代码来检测并重定向用户:
if((navigator.userAgent.match(/iPhone/i)) || 
                (navigator.userAgent.match(/Android/i)) ||
                (navigator.userAgent.match(/iPod/i))) 
        { 
        window.location = "http://sitename.com/m/";
    }

在iPhone和iPod上运行良好,但在Android上没有成功。我正在使用Eclipse中的Android模拟器。我没有Android设备来实际测试它。

我做错了什么吗?有人遇到同样的问题吗?

2个回答

12

你应该使用 location.replace 而不是 window.location

示例:

if( (navigator.userAgent.match(/iPhone/i)) || (navigator.userAgent.match(/Android/i)) || (navigator.userAgent.match(/iPod/i)) ) { 
    location.replace("http://sitename.com/m/");
}

我使用了这段代码,在 iPhone/iTouch 和 Android 手机/设备上都可以正常运行。


这也帮了我很多。只是要明确一点,似乎在Android上不支持windows.location。location.replace()可以正常工作。 - Symmetric

3

这里是我用 JavaScript 编写的检测 Android 设备的函数:

function isAndroid() {
    var ua = navigator.userAgent;
    return ua.match(/Android/) 
        || ua.match(/Dalvik/)
        || ua.match(/GINGERBREAD/)
        || ua.match(/Linux;.*Mobile Safari/)
        || ua.match(/Linux 1\..*AppleWebKit/)
};

1
谢谢您,先生。我一直在寻找这个。 - nym

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接