Detect if device is iOS

前端 未结 17 1576
一整个雨季
一整个雨季 2020-11-22 01:39

I\'m wondering if it\'s possible to detect whether a browser is running on iOS, similar to how you can feature detect with Modernizr (although this is obviously device detec

相关标签:
17条回答
  • 2020-11-22 02:22

    A simplified, easy to extend version.

    var iOS = ['iPad', 'iPhone', 'iPod'].indexOf(navigator.platform) >= 0;
    
    0 讨论(0)
  • 2020-11-22 02:22

    Detecting iOS (both <12, and 13+)

    Community wiki, as edit queue says it is full and all other answers are currently outdated or incomplete.

    const iOS_1to12 = /iPad|iPhone|iPod/.test(navigator.platform);
    
    const iOS13_iPad = (navigator.platform === 'MacIntel' && navigator.maxTouchPoints > 1));
    
    const iOS1to12quirk = function() {
      var audio = new Audio(); // temporary Audio object
      audio.volume = 0.5; // has no effect on iOS <= 12
      return audio.volume === 1;
    };
    
    const isIOS = !window.MSStream && (iOS_1to12 || iOS13_iPad || iOS1to12quirk());
    
    0 讨论(0)
  • 2020-11-22 02:23

    Wow, a lot of longish tricky code here. Keep it simple, please!

    This one is IMHO fast, save, and working well:

     iOS = /^iP/.test(navigator.platform);
    
     // or, more future-proof (in theory, probably not in practice):
    
     iOS = /^iP(hone|[ao]d)/.test(navigator.platform);
    
     // or, if you prefer readability:
    
     iOS = /^(iPhone|iPad|iPod)/.test(navigator.platform);
    
    • It's fast because the regexp checks the ^starting position of the platform string first and stops if there is no "iP" (faster than searching the long UA string until the end anyway)
    • It's safer than UA check (assuming navigator.platform is less likely faked)
    • Detects iPhone / iPad Simulator


    UPDATE: This doesn't cover iPad in desktop mode (and therefore default iPadOS 13).
    That's fine for my usecases, if it's not for you, see Justin's and kikiwora's answers.

    0 讨论(0)
  • 2020-11-22 02:23

    In order to detect the iOS version, one has to destructure the user agent with a Javascript code like this:

     var res = navigator.userAgent.match(/; CPU.*OS (\d_\d)/);
        if(res) {
            var strVer = res[res.length-1];
            strVer = strVer.replace("_", ".");
            version = strVer * 1;
        }
    
    0 讨论(0)
  • 2020-11-22 02:26

    If you are using Modernizr, you can add a custom test for it.

    It doesn't matter which detection mode you decide to use (userAgent, navigator.vendor or navigator.platform), you can always wrap it up for a easier use later.

    //Add Modernizr test
    Modernizr.addTest('isios', function() {
        return navigator.userAgent.match(/(iPad|iPhone|iPod)/g);
    });
    
    //usage
    if (Modernizr.isios) {
        //this adds ios class to body
        Modernizr.prefixed('ios');
    } else {
        //this adds notios class to body
        Modernizr.prefixed('notios');
    }
    
    0 讨论(0)
提交回复
热议问题