如何最好地检测我的网站是否通过移动设备访问

时间:2014-12-22 23:30:12

标签: javascript python mobile browser

我有一个基于python的网站(在app-engine上)。这意味着我的服务器是用python编写的,我使用通常的webapp2和jinja2来帮助我的页面服务。我想要完成的是取决于是否有人通过iPhone,Android或普通计算机(即台式机或笔记本电脑)访问我的网站,以适当的格式服务网页"。我想我有很多方法可以做到这一点

  1. 我可以通过JavaScript完成,然后重定向到相应的" mobile"网址
  2. 或者我可以在Python中完成并提供正确的页面
  3. 2中的含义与

    类似
    class ServeMyPage(webapp2.RequestHandler):
        def get(self):
          //...do some work to determine the device, such as screen size
          if device==iPhone
            //...get the iPhone page and serve it
            self.response.out.write(iPhonePage);
          else ...// etc, etc
    

    在我的代码片段中,我在为页面提供服务之前就这样做了。我想这更快,因为它不等待页面加载,然后检查一些JavaScript,看看我是否应该将内容更改为适当的格式。我希望这很清楚。

    那么最好的方法是什么?我应该用JavaScript吗?其他一些方式?还是我在上面展示的?如上所示,代码可能是什么样的?我的问题也是技术问题,因为我不知道在Python中放入什么代码。感谢。

2 个答案:

答案 0 :(得分:2)

您可以使用modernizr's触摸检测来检查它是否是触摸设备,如果是,则您有一个移动点。

if (Modernizr.touch) {

}
else 
{
    code for non mobile device
}

然后,您可以检查用户代理(这可能不是您的最佳选择,因为用户代理并不总是可靠),并编写一个简单的if else,代码只能在非移动设备上执行其他

  var isMobile = {
            Android: function () {
                return navigator.userAgent.match(/Android/i);
            },
            BlackBerry: function () {
                return navigator.userAgent.match(/BlackBerry/i);
            },
            iOS: function () {
                return navigator.userAgent.match(/iPhone|iPad|iPod/i);
            },
            Opera: function () {
                return navigator.userAgent.match(/Opera Mini/i);
            },
            Windows: function () {
                return navigator.userAgent.match(/IEMobile/i);
            },
            any: function () {
                return (isMobile.Android() || isMobile.BlackBerry() || isMobile.iOS() || isMobile.Opera() || isMobile.Windows());
            }
        };

        if (isMobile.any()) {

        }
        else {

             not mobile
        }

另一种测试方法是检查window.innerWidth,如果屏幕尺寸大于760px,则只启动脚本:

if (window.innerWidth > 760) {
not mobile
}

这样做的一个好方法是将上面的3个语句结合起来进行检查。

答案 1 :(得分:1)

您可以使用WURFL API来检测设备类型

http://wurfl.sourceforge.net/wurfl_schema.php