Detect mobile client in webgl

Viewed 358

I need to detect whether the user is running a webgl app in a mobile browser or on a desktop/laptop browser. Is this possible to detect using the Unity API, or you need to do some HTML hack?

2 Answers

There is a "hack" for this. You can find out via JavaScript so you just need a plugin connection between the c# and JavaScript e.g. using the Navigator.userAgent somewhat like

var HandleIO = {
    IsMobilePlatform : function()
    {
        var userAgent = navigator.userAgent;
        isMobile = (
                    /\b(BlackBerry|webOS|iPhone|IEMobile)\b/i.test(userAgent) ||
                    /\b(Android|Windows Phone|iPad|iPod)\b/i.test(userAgent) ||
                    // iPad on iOS 13 detection
                    (userAgent.includes("Mac") && "ontouchend" in document)
                );
        return isMobile;
    }
};
mergeInto(LibraryManager.library, HandleIO);

put this e.g. in a folder like Assets/WebGL/Plugins an make sure to only compile it for WebGL

enter image description here

and then on the c# side you could include like e.g.

using System;
#if UNITY_WEBGL
using System.Runtime.InteropServices;
#endif
using UnityEngine;

public class WebGLBrowserCheck : MonoBehaviour
{
#if UNITY_WEBGL
    [DllImport("__Internal")]
    static extern bool IsMobilePlatform();

    public static bool IsMobileBrowser()
    {
#if UNITY_EDITOR
        return false; // value to return in Play Mode (in the editor)
#elif UNITY_WEBGL
        return IsMobilePlatform(); // value based on the current browser
#else
        return false;
#endif
    }
#endif
}

so later on you just call

var isMobile = WebGLBrowserCheck.IsMobileBrowser();

Of course there are more mobile phones and OS then the listed ones so you might want to extend it if needed but these should cover the most common ones

I think you are after preprocessor directives. They take place before compiling your code to pre-select the code that needs to be run according the platform you are working building on. Thats why they're also called conditional compilation directives.

For example:

#if UNITY_EDITOR || UNITY_WEBGL
 //this code will be compiled and run while in editor or webgl build target in the build settings
#endif

#if UNITY_ANDROID 
 //this code will be compiled and run when the build target is set to android in the build settings
#endif

To detect which device your app is running in in the browser you need to use the Navigator.userAgent Check also the windowNavigator

You can check out also libraries that do that for you, such as this

Related