我如何检测用户是否正在从移动网络浏览器浏览我的网站,以便我可以自动检测和显示我的网站的适当版本?
当前回答
移动设备浏览器文件是检测移动(和其他)ASP浏览器的好方法。NET项目:http://mdbf.codeplex.com/
其他回答
你还没说你在用什么语言。如果是Perl,那么它很简单:
use CGI::Info;
my $info = CGI::Info->new();
if($info->is_mobile()) {
# Add mobile stuff
}
unless($info->is_mobile()) {
# Don't do some things on a mobile
}
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.
移动设备浏览器文件是检测移动(和其他)ASP浏览器的好方法。NET项目:http://mdbf.codeplex.com/
是的,读取User-Agent报头就可以了。
有一些已知的移动用户代理列表,所以您不需要从头开始。当我不得不这样做时,我所做的是建立一个已知用户代理的数据库,并在检测到需要修改的未知数据时存储它们,然后手动找出它们是什么。在某些情况下,最后一项可能太过了。
如果希望在Apache级别上执行该操作,可以创建一个脚本,定期生成一组重写规则,检查用户代理(或者只检查一次,不考虑新的用户代理,或者每月检查一次,取决于您的情况),例如
RewriteEngine On
RewriteCond %{HTTP_USER_AGENT} (OneMobileUserAgent|AnotherMobileUserAgent|...)
RewriteRule (.*) mobile/$1
例如,将请求移到http://domain/index.html到http://domain/mobile/index.html
如果你不喜欢让脚本定期重新创建htaccess文件的方法,你可以写一个模块来检查用户代理(我没有找到一个已经创建的,但找到了这个特别合适的例子),并从一些站点获取用户代理来更新它们。然后你可以把这个方法尽可能复杂化,但我认为在你的情况下,之前的方法就可以了。
在检测移动浏览器上有开源脚本,可以在Apache、ASP、ColdFusion、JavaScript和PHP中实现这一点。