Html 自动检测移动浏览器(通过用户代理?)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1005153/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 23:55:08  来源:igfitidea点击:

Auto detect mobile browser (via user-agent?)

htmlwindows-mobilebrowseruser-agent

提问by

How can I detect if a user is viewing my web site from a mobile web browser so that I can then auto detect and display the appropriate version of my web site?

如何检测用户是否正在从移动网络浏览器查看我的网站,以便我可以自动检测并显示我的网站的适当版本?

采纳答案by Vinko Vrsalovic

Yes, reading the User-Agent header will do the trick.

是的,阅读 User-Agent 标头就可以解决问题。

There are some listsoutthere of known mobile user agents so you don't need to start from scratch. What I did when I had to is to build a database of known user agents and store unknowns as they are detected for revision and then manually figure out what they are. This last thing might be overkill in some cases.

有一些已知的移动用户代理列表因此您无需从头开始。当我不得不这样做时,我所做的是建立一个已知用户代理的数据库,并在检测到待修订时存储未知数,然后手动找出它们是什么。在某些情况下,最后一件事可能是矫枉过正。

If you want to do it at Apache level, you can create a script which periodically generates a set of rewrite rules checking the user agent (or just once and forget about new user agents, or once a month, whatever suits your case), like

如果您想在 Apache 级别执行此操作,您可以创建一个脚本,该脚本会定期生成一组重写规则来检查用户代理(或仅一次而忘记新的用户代理,或每月一次,无论适合您的情况),例如

RewriteEngine On

RewriteCond %{HTTP_USER_AGENT} (OneMobileUserAgent|AnotherMobileUserAgent|...)
RewriteRule (.*) mobile/

which would move, for example, requests to http://domain/index.htmlto http://domain/mobile/index.html

例如,这会将请求移动到http://domain/index.htmlhttp://domain/mobile/index.html

If you don't like the approach of having a script recreate a htaccess file periodically, you can write a module which checks the User Agent (I didn't find one already made, but found this particularly appropriate example) and get the user agents from some sites to update them. Then you can complicate the approach as much as you want, but I think in your case the previous approach would be fine.

如果您不喜欢让脚本定期重新创建 htaccess 文件的方法,您可以编写一个模块来检查用户代理(我没有找到已经制作的模块,但找到了这个特别合适的示例)并获取用户代理从某些站点更新它们。然后你可以根据需要使方法复杂化,但我认为在你的情况下,以前的方法会很好。

回答by Chad Smith

There are open source scripts on Detect Mobile Browserthat do this in Apache, ASP, ColdFusion, JavaScript and PHP.

Detect Mobile Browser上有开源脚本,可以在 Apache、ASP、ColdFusion、JavaScript 和 PHP 中执行此操作。

回答by midsever

Just a thought but what if you worked this problem from the opposite direction? Rather than determining which browsers are mobile why not determine which browsers are not? Then code your site to default to the mobile version and redirect to the standard version. There are two basic possibilities when looking at a mobile browser. Either it has javascript support or it doesn't. So if the browser does not have javascript support it will default to the mobile version. If it does have JavaScript support, check the screen size. Anything below a certain size will likely also be a mobile browser. Anything larger will get redirected to your standard layout. Then all you need to do is determine if the user with JavaScript disabled is mobile or not.
According to the W3C the number of users with JavaScript disabled was about 5% and of those users most have turned it off which implies that they actually know what they are doing with a browser. Are they a large part of your audience? If not then don't worry about them. If so, whats the worst case scenario? You have those users browsing the mobile version of your site, and that's a good thing.

只是一个想法,但如果你从相反的方向解决这个问题怎么办?与其确定哪些浏览器是移动的,为什么不确定哪些浏览器不是?然后将您的网站编码为默认为移动版本并重定向到标准版本。查看移动浏览器时有两种基本可能性。它要么支持javascript,要么不支持。因此,如果浏览器没有 javascript 支持,它将默认为移动版本。如果它确实支持 JavaScript,请检查屏幕大小。任何低于特定大小的东西也可能是移动浏览器。任何更大的东西都会被重定向到你的标准布局。然后您需要做的就是确定禁用 JavaScript 的用户是否是移动用户。
根据 W3C 的数据,禁用 JavaScript 的用户数量约为 5%,其中大多数用户已将其关闭,这意味着他们实际上知道他们在用浏览器做什么。他们是你的观众的很大一部分吗?如果没有,那么不要担心他们。如果是这样,最坏的情况是什么?您让这些用户浏览您网站的移动版本,这是一件好事。

回答by Ed Poor

Here's how I do it in JavaScript:

下面是我在 JavaScript 中的做法:

function isMobile() {
  var index = navigator.appVersion.indexOf("Mobile");
  return (index > -1);
}

See an example at www.tablemaker.net/test/mobile.htmlwhere it triples the font size on mobile phones.

请参阅www.tablemaker.net/test/mobile.html上的示例,其中将手机上的字体大小增加了两倍。

回答by Cory

Have you considered using css3 media queries? In most cases you can apply some css styles specifically for the targeted device without having to create a separate mobile version of the site.

您是否考虑过使用 css3 媒体查询?在大多数情况下,您可以专门为目标设备应用一些 css 样式,而无需创建网站的单独移动版本。

@media screen and (max-width:1025px) {
   #content {
     width: 100%;
   }
}

You can set the width to whatever you want, but 1025 will catch the iPad landscape view.

您可以将宽度设置为您想要的任何值,但 1025 会捕捉 iPad 的横向视图。

You'll also want to add the following meta tag to your head:

您还需要将以下元标记添加到您的头部:

<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">

Check out this articleover at HTML5 Rocks for some good examples

在 HTML5 Rocks 上查看这篇文章以获得一些很好的示例

回答by Pablo Santa Cruz

My favorite Mobile Browser Detection mechanism is WURFL. It's updated frequently and it works with every major programming/language platform.

我最喜欢的移动浏览器检测机制是WURFL。它经常更新,适用于每个主要的编程/语言平台。

回答by Jorgesys

for ANDROID , IPHONE, IPAD, BLACKBERRY, PALM, WINDOWS CE, PALM

适用于安卓、IPHONE、IPAD、黑莓、PALM、WINDOWS CE、PALM

 <script language="javascript"> <!--
     var mobile = (/iphone|ipad|ipod|android|blackberry|mini|windows\sce|palm/i.test(navigator.userAgent.toLowerCase()));
              if (mobile) {
                  alert("MOBILE DEVICE DETECTED");
                  document.write("<b>------------------------------------------<br>")
                  document.write("<b>" + navigator.userAgent + "<br>")
                  document.write("<b>------------------------------------------<br>")
                  var userAgent = navigator.userAgent.toLowerCase();
                  if ((userAgent.search("android") > -1) && (userAgent.search("mobile") > -1))
                         document.write("<b> ANDROID MOBILE <br>")
                   else if ((userAgent.search("android") > -1) && !(userAgent.search("mobile") > -1))
                       document.write("<b> ANDROID TABLET <br>")
                   else if ((userAgent.search("blackberry") > -1))
                       document.write("<b> BLACKBERRY DEVICE <br>")
                   else if ((userAgent.search("iphone") > -1))
                       document.write("<b> IPHONE DEVICE <br>")              
                   else if ((userAgent.search("ipod") > -1))
                       document.write("<b> IPOD DEVICE <br>")
               else if ((userAgent.search("ipad") > -1))
                       document.write("<b> IPAD DEVICE <br>")
                       else
                   document.write("<b> UNKNOWN DEVICE <br>")
              }
              else
                  alert("NO MOBILE DEVICE DETECTED"); //--> </script>

回答by mjf

The Mobile Device Browser File is a great way to detect mobile (and other) broswers for ASP.NET projects: http://mdbf.codeplex.com/

移动设备浏览器文件是检测 ASP.NET 项目的移动(和其他)浏览器的好方法:http://mdbf.codeplex.com/

回答by sohel khalifa

You can detect mobile clients simply through navigator.userAgent, and load alternate scripts based on the detected client type as:

您可以简单地通过 检测移动客户端 navigator.userAgent,并根据检测到的客户端类型加载备用脚本:

 $(document).ready(function(e) {

        if(navigator.userAgent.match(/Android/i)
          || navigator.userAgent.match(/webOS/i)
          || navigator.userAgent.match(/iPhone/i)
          || navigator.userAgent.match(/iPad/i)
          || navigator.userAgent.match(/iPod/i)
          || navigator.userAgent.match(/BlackBerry/i)
          || navigator.userAgent.match(/Windows Phone/i)) {

         //write code for your mobile clients here.

          var jsScript = document.createElement("script");
          jsScript.setAttribute("type", "text/javascript");
          jsScript.setAttribute("src", "js/alternate_js_file.js");
          document.getElementsByTagName("head")[0].appendChild(jsScript );

          var cssScript = document.createElement("link");
          cssScript.setAttribute("rel", "stylesheet");
          cssScript.setAttribute("type", "text/css");
          cssScript.setAttribute("href", "css/alternate_css_file.css");
          document.getElementsByTagName("head")[0].appendChild(cssScript); 

    }
    else{
         // write code for your desktop clients here
    }

    });

回答by sebarmeli

You can check the User-Agent string. In JavaScript, that's really easy, it's just a property of the navigator object.

您可以检查用户代理字符串。在 JavaScript 中,这真的很简单,它只是 navigator 对象的一个​​属性。

var useragent = navigator.userAgent;

You can check if the device if iPhone or Blackberry in JS with something like

您可以检查设备是否是 iPhone 或 JS 中的黑莓,例如

var isIphone = !!agent.match(/iPhone/i),
    isBlackberry = !!agent.match(/blackberry/i);

if isIphone is true you are accessing the site from an Iphone, if isBlackBerry you are accessing the site from a Blackberry.

如果 isIphone 为真,则您正在从 Iphone 访问该站点,如果 isBlackBerry,则您正在从黑莓访问该站点。

You can use "UserAgent Switcher" plugin for firefox to test that.

您可以使用 firefox 的“UserAgent Switcher”插件来测试。

If you are also interested, it may be worth it checking out my script "redirection_mobile.js"hosted on github here https://github.com/sebarmeli/JS-Redirection-Mobile-Siteand you can read more details in one of my article here:

如果您也有兴趣,可能值得查看我在 github 上托管的脚本“redirection_mobile.js” https://github.com/sebarmeli/JS-Redirection-Mobile-Site,您可以在其中之一中阅读更多详细信息我的文章在这里:

http://blog.sebarmeli.com/2010/11/02/how-to-redirect-your-site-to-a-mobile-version-through-javascript/

http://blog.sebarmeli.com/2010/11/02/how-to-redirect-your-site-to-a-mobile-version-through-javascript/