JavaScript: Detect Mobile Webbrowser

Veröffentlicht am Autor JonasHinterlasse einen Kommentar

There are many ways and functions to detect if a device is a mobile one.

Here is mine, having no need for a database of user agents and also not depending on page ratio (yes works also on modern tablets).

Objectives: to have something small, efficient and reliable.

/**
 * Returns True when browser is a mobile one.
 * @param {String} user_agent - navigator.UserAgent of browser
 * @param {Array} list_of_mobile_keywords - array of mobile keywords
 */
function Is_Mobile_Browser(user_agent, list_of_mobile_keywords)
{
    // Look for Mobile tag
    // E.g. Mobile Safari:
    // Mozilla/5.0 (iPhone; CPU iPhone OS 12_2 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15E148
    if (user_agent.includes("Mobile") || user_agent.includes("mobile"))
    {
        return true;
    }

    // Checks if Browser runs on Android
    if(user_agent.includes("Android"))
    {
        return true;
    }

    // If no result check CPU architecture
    // x86_64 and x86 -> Desktop
    // Android x86 devices should be detected by check before
    if (user_agent.includes("x86"))
    {
        return false;
    }

    // If no mobile tag was set look for mobile keywords
    for (var i = 0; list_of_mobile_keywords.length >= i; ++i)
    {
        if (user_agent.includes(list_of_mobile_keywords[i]))
        {
            return true;
        }
    }

    // Case: Still no decision was made
    return false;
}

/* List of mobile keywords
   Sorted according to likelihood of occurrence. */
// Keyword explanation:
// QtCarBrowser - Tesla Car
// Opera Mini - Opera Mini is the only webrowser on android not telling that it's running on android.
// Web0S - Some TV's (remote control and mobile webpages are a perfect fit)
// SmartTV - Apple TV and some other SmartTV's
var list_of_mobile_keywords = ["iOS", "iPhone", "iPad", "Opera Mini", "Phone", "Kindle", "SmartTV", "PlayStation", "Web0S", "QtCarBrowser", "IEMobile", "SamsungBrowser"];

// Run the detection function
Is_Mobile_Browser(navigator.userAgent.toString(), list_of_mobile_keywords);

 

I tested it by a hand full of devices having multiple browsers installed, also I faked some user agents with my desktop browser in order to test the function.

 

 



Schreibe einen Kommentar

Deine E-Mail-Adresse wird nicht veröffentlicht. Erforderliche Felder sind mit * markiert.