Alex Rivera | Logout

Detect Desktop Browser (not mobile) with Javascript

Asked 2011-11-03T13:31:21.037
32

I found the following code to detect a desktop browser. But the method also detects some mobile browsers. How can I detect only desktop browsers like Safari, IE, Firefox, Opera etc?

is_desktopBrowser : function() {
    var ua = navigator.userAgent.toLowerCase();

    var rwebkit = /(webkit)[ \/]([\w.]+)/;
    var ropera = /(opera)(?:.*version)?[ \/]([\w.]+)/;
    var rmsie = /(msie) ([\w.]+)/;
    var rmozilla = /(mozilla)(?:.*? rv:([\w.]+))?/;

    var match = rwebkit.exec(ua) ||
            ropera.exec(ua) ||
            rmsie.exec(ua) ||
            ua.indexOf("compatible") < 0 && rmozilla.exec(ua) ||
            [];

    return { browser: match[1] || "", version: match[2] || "0" };
},
Edit
Report

1 Answer

12

I came up with this:

    var isTouchDevice = function() {  return 'ontouchstart' in window || 'onmsgesturechange' in window; };
    var isDesktop = window.screenX != 0 && !isTouchDevice() ? true : false;

It leverages two things we can hold on to. One, window.screenX will ALWAYS be 0 on any tablet / mobile device. You can't move windows on these devices, it is always full screen.

Two, isTouchDevice is a pretty reliable way to know if it's mobile (android / iphone tablet) or Windows Surfacey thing. It has a touch event. Combining the two gives us a high degree of certainty that it's a mobile or tablet. If you're not one of those, you must be desktop.

Yes, you might have a desktop that somehow reports itself as touch and has the browser maxxed to the upper left. In my case, I can let that go.

answered 2013-01-11T17:38:21.160

Your Answer