Detecting mobile device "notch"

kinggs picture kinggs · Sep 20, 2017 · Viewed 16.7k times · Source

With the launch of the iPhone X imminent, I'm trying to get ahead of the game and prepare some of my web applications to handle any design changes - the biggest of which being the new "notch" which houses the front camera.

I was wondering whether there is, or likely to be, any way of detecting this in Javascript somehow.

Interestingly, Chris Coyier has written an article about The "Notch" and CSS which led me to discover the safe-area-inset-right constant. Is there any way this can be accessed in Javascript and is this a reliable test.

if (window.constant.safeAreaInsetRight) {
  var notch = true;
}

Answer

Adrian picture Adrian · Sep 22, 2017

This might be a little hacky however, obtaining the screen available heights and widths and matching them to this specifications would allow us to determine if it is an iPhone X.

Please note

In portrait orientation, the width of the display on iPhone X matches the width of the 4.7" displays of iPhone 6, iPhone 7, and iPhone 8. The display on iPhone X, however, is 145pt taller than a 4.7" display...

enter image description here

So, firstly, you want to check if it is an iPhone via the userAgent, secondly you would check the area of the actual screen (excluding the orientation which defaults to portrait), lastly, once we know that it is an iPhoneX via it's screen dimensions you can determine the orientation (based on the table under the iPhone X diagram above)

if (navigator.userAgent.match(/(iPhone)/)){
  if((screen.availHeight == 812) && (screen.availWidth == 375)){

    if((window.innerHeight == "375") && (window.innerWidth == "812")){
      // iPhone X Landscape

    }else{
      // iPhone X Portrait
    }
  }
}

References:

avilHeight

avilWidth

iPhoneX Specs

As for CSS solution, I have found an interesting article about it yesterday which might be of use

Let’s say you have a fixed position header bar, and your CSS for iOS 10 currently looks like this:

header {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    height: 44px;

    padding-top: 20px; /* Status bar height */
}

To make that adjust automatically for iPhone X and other iOS 11 devices, you would add a viewport-fit=cover option to your viewport meta tag, and change the CSS to reference the constant:

header {
    /* ... */

    /* Status bar height on iOS 10 */
    padding-top: 20px;

    /* Status bar height on iOS 11+ */
    padding-top: constant(safe-area-inset-top);
}

It’s important to keep the fallback value there for older devices that won’t know how to interpret the constant() syntax. You can also use constants in CSS calc() expressions.

Article