Detect whether an iOS device has a home bar using JS or CSS

Viewed 3269

I am building a web app for iOS, and want to know if it's possible using JS or CSS to detect whether a device has the on-screen Home Bar at the bottom (i.e. an iPhone X, 11, or iPad Pro - with rounded corners and no home button).

Because if creating a tab bar, I need to know whether or not to add the additional padding at the bottom to accommodate this, as illustrated in the image below.

enter image description here

Short of using media queries to detect from a list of EXACT screen resolutions for these devices and hoping for the best, I can't come up with a solution.

Any ideas out there?

1 Answers

Working from this post, I was able to calculate the height of the bottom safe area, thus determining whether the home bar is present. If you return a non-zero pixel value, the home bar is (probably) there. If it returns 0px, no home bar.

Definitely read the linked post, but the general idea is that you'll set the CSS env() function to the :root element and then read the calculated value back.

Here's how it works:

First, you'll need to use the whole available screen by putting this in the <head> section of your document:

<meta name="viewport" content="viewport-fit=cover" />

Then, add to your CSS:

:root {
    --sat: env(safe-area-inset-top);
    --sar: env(safe-area-inset-right);
    --sab: env(safe-area-inset-bottom); /* THIS ONE GETS US THE HOME BAR HEIGHT */
    --sal: env(safe-area-inset-left);
}

Finally, read back the value in Javascript:

getComputedStyle(document.documentElement).getPropertyValue("--sab")

This should return a value like 34px when the home bar is present and 0px when it ain't.

Related