3 ways to implement JavaScript to determine mobile and PC-side access to different websites

Source: Internet
Author: User

3 methods are relatively simple, add the following JS code in the header of the page:

    1. For simply jumping directly from www.maslinkcom to M.maslink.com, this method is only available from the home page:
<script> (function () {
var url = location.href;
Replace www.maslink.com with your domain
if ((Url.indexof (' www.maslink.com ')! =-1) &&
Navigator.userAgent.match (/(iphone|ipod| Android|ios|ipad)/i))
{location.href = ' http://m.maslink.com ';
}
})();
</script>

2. If the site in addition to the home section, followed by the following, such as: www.maslink.com/list/98/, for such a url,pc directly such access, for the mobile side, only need to through the m.maslink.com/list/98/ Can show a better effect. Replace the http://www with http://m, and then update the page to see how the page will appear on the mobile side.

<script>
(function () {
var url = location.href;
Replace www.maslink.com with your domain
if ((Url.indexof (' www.maslink.com ')! =-1) &&
Navigator.userAgent.match (/(iphone|ipod| Android|ios|ipad)/i))
{var newurl = url.replace (' http://www ', ' http://m ');
Location.href = Newurl;
}
})();
</script>

3. Another option is to give hints when accessing a mobile device:

<script>
var useragentinfo = navigator.useragent;
var Agents = new Array ("Android", "IPhone", "SymbianOS", "Windows Phone",
"IPad", "IPod");
var flag = false;
var v=0
for (v = 0; v < agents.length; v++)
{
if (Useragentinfo.indexof (AGENTS[V) > 0)
{flag = true; break;}
}
if (flag) {
window.location.href= "Http://m.maslink.com"
Alert (Agents[v]);//device type
}
Else
{
Pc
}
</script>

The above three methods are I tested in the test, simple operation, the effect is obvious, I hope readers can use

3 ways to implement JavaScript to determine mobile and PC-side access to different websites

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.