简单的javascript检测用户的设备

时间:2012-04-23 23:59:16

标签: javascript iphone

我想在我的模板中添加javascript,以便每次用户使用何种设备(智能手机,平板电脑或PC)查看我的网站时都会检测到。

目前,我尝试使用javascript,这里是:

var smartPhone = "smartphone";
var Ipod = "ipod";

var userDevice = navigator.userAgent.toLowerCase();

function DetectPhone()
{
   if (userDevice.search(smartPhone) > -1)
      return true;
   else
      windows.location = "/pageforphone.aspx";
}

function DetectIpod()
{
   if (userDevice.search(Ipod) > -1)
      return true;
   else
      windows.location = "/pageforpod.aspx";
}

我是否正确编写了代码?老实说,没有iPhone ......

当然,如果用Php或Asp.net完成这些会更好,但人们总是在手掌设备上关闭javascript是真的吗? 另外,我认为iphone或ipod或任何其他平板电脑非常相似,我可以使用相同的重新设置页面吗?实际上我并不是很了解他们之间的差异以及我在重新设置网页时应该注意什么。

3 个答案:

答案 0 :(得分:1)

问题的前提是,浏览器嗅探是可以接受的,是错误的。你永远不应该参与浏览器嗅探,因为你无法自信地完成你想要完成的任务。用户代理字符串不是不可变的,并且通常会被安装在客户端计算机上的插件或客户端本身改变(这并不罕见,因为糟糕的程序员可能会根据他们的UA-String将它们锁定在站点之外)。

而不是要求用户是哪个设备,而应该要求设备能够使用。这将带您进入功能检测,在那里你开始做X,测试用户代理是否能够做X,然后继续做或不做X.例如:

if ( !!document.createElement("video").canPlayType ) {
  console.log( "HTML5 Video Supported" );
}

这比尝试查看用户是否在iPhone,iPad,Windows平板电脑或HTML5启用浏览器上更可靠。您可以使用Modernizr之类的工具为您执行大量的测试 - 实际上超过40个。

答案 1 :(得分:0)

市场上有许多移动设备+每个设备可以安装多个浏览器。我更喜欢使用一些库,而不是在用户代理字符串中为“iPhone”提供资金(我自己使用Android手机和Opera浏览器)

例如:

它们都会定期更新,发布最新的移动设备,并为您提供特定设备支持的功能信息

答案 2 :(得分:-1)

这是我使用javascript检测iOS设备的方式

<script type="text/javascript">
    var agent = navigator.userAgent.toLowerCase();
    var isiPhone = ((agent.indexOf('iphone'))!=-1)

    if (((agent.indexOf('iphone'))!=-1) {
        document.location = "mobile.aspx?device=iphone";
    }

    if (((agent.indexOf('ipod'))!=-1) {
        document.location = "mobile.aspx?device=ipod";
    }

    if (((agent.indexOf('iPad'))!=-1) {
        document.location = "mobile.aspx?device=ipad";
    }
</script>