[英]How can I redirect mobile devices to a different URL?
I want to check whether the user is viewing my site from a mobile device or PC. 我想检查用户是否正在从移动设备或PC查看我的网站。 If it's a mobile device, I want to redirect my site URL like Google does... 如果是移动设备,我想像Google一样重定向网站网址...
If possible I would like to implement this in JavaScript. 如果可能的话,我想用JavaScript来实现。 How can I do this? 我怎样才能做到这一点?
You typically use the User-Agent header to detect the browser. 通常,您使用User-Agent标头检测浏览器。
Here's JavaScript code that does basically that (only for mainstream browsers though, you'd have to add the Mobile User-Agents) 这是基本上做到这一点的JavaScript代码(尽管仅适用于主流浏览器,您必须添加移动用户代理)
http://www.quirksmode.org/js/detect.html http://www.quirksmode.org/js/detect.html
And here's a list of mobile browser identifiers 这是移动浏览器标识符的列表
http://www.zytrax.com/tech/web/mobile_ids.html http://www.zytrax.com/tech/web/mobile_ids.html
The list is not complete and will never be, given the rate new mobiles appear on the market, but what I did back when I did it is to store all received user agents in a database, and then look for them to classify them as mobile and which brand/model. 考虑到新手机在市场上的普及率,该列表并不完整,而且永远不会出现,但是我回来时所做的是将所有收到的用户代理存储在数据库中,然后寻找他们将其归类为手机以及哪个品牌/型号。
What you can't rely on though is JavaScript, it's better done in server code (not all mobile browsers execute JavaScript). 不过,您不能依靠的是JavaScript,最好用服务器代码完成(并非所有移动浏览器都执行JavaScript)。
There is a related question here on SO but I couldn't find it. SO上有一个相关的问题,但我找不到。
See this existing question . 看到这个现有的问题 。
You will have better luck doing this server side, as many mobile browsers don't even support JavaScript. 由于许多移动浏览器甚至不支持JavaScript,因此您在服务器端做的比较好。 Basically you want to check the user agent and compare to a list of known mobile browsers. 基本上,您想检查用户代理并与已知的移动浏览器列表进行比较。
Here is a simple answer for this query. 这是此查询的简单答案。 This won't detect the mobile browser, but it redirects the page to our mobile.html
page, through the following script; 这不会检测到移动浏览器,但是会通过以下脚本将页面重定向到我们的mobile.html
页面;
Find out the browser window size and redirect it.. 找出浏览器窗口大小并重定向。
winWidth=document.all?document.body.clientwidth:window.innderwidth;
if (winwidth<800)
{
window.location.replace("mobile.html");
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.