Auto detect mobile browser (via user
如何检测用户是否正在通过移动Web浏览器查看我的网站,以便我可以自动检测并显示我的网站的相应版本?
Yes, reading the User-Agent header will do the trick.
There are some lists out there 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
RewriteEngine On
RewriteCond %{HTTP_USER_AGENT} (OneMobileUserAgent|AnotherMobileUserAgent|...)
RewriteRule (.*) mobile/$1
which would move, for example, requests to http://domain/index.html to http://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.
Detect Mobile Browser上有开源脚本,可以在Apache,ASP,ColdFusion,JavaScript和PHP中执行此操作。
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.
上一篇: 当您在浏览器中输入网址时会发生什么情况
下一篇: 自动检测手机浏览器(通过用户