Detecting Mobile vs Desktop in JavaScript and Routing Visitors to the Right Site

Detecting mobile vs desktop visits

Plenty of sites still run two separate builds — a desktop one and a mobile one (responsive sites aside). With two builds, you have to know what the visitor is on: desktop goes to the desktop site, everything else goes to the mobile one.

User-agent sniffing solves this, and it can be done in front-end JS or on the server. This post focuses on the JS approach.

Say a site lives at www.a.com for desktop and m.a.com for mobile. All you need is for mobile visitors hitting www.a.com to land on m.a.com. Add this to the page head:

(function () {
    var url = location.href;
    // replace www.a.com with your domain
    if ( (url.indexOf('www.a.com') != -1) && navigator.userAgent.match(/(iPhone|iPod|Android|ios|iPad)/i) ) {
        location.href = 'http://m.a.com';
    }
})();

Often, though, it isn't that clean — you're not bouncing www.a.com to m.a.com wholesale. URLs carry a path after the hostname, like www.a.com/list/98/. Desktop handles that fine; mobile visitors need m.a.com/list/98/ to get a decent layout.

A regex handles that: on mobile, swap http://www for http://m and reload. The page then renders properly on the phone. Here's the code:

(function () {
    var url = location.href;
    // replace www.a.com with your domain
    if ( (url.indexOf('www.a.com') != -1) && navigator.userAgent.match(/(iPhone|iPod|Android|ios|iPad)/i) ) {
        var newUrl = url.replace('http://www', 'http://m');
        location.href = newUrl;
    }
})();

That covers routing mobile visitors to the mobile build.

Leave a Comment

Comments 1

  • QQ极客
    QQ极客 2017-11-07 15:39 Reply

    那假如移动端是动态的 有好的解决方法么

Table of Contents