Get safe-area-inset-bottom on page load

Viewed 1265

I am using the code below to get the safe area at the bottom of the iPhone.

If I call getSafeArea() immediately after deviceready, it sometimes returns 0 instead of the desired value. Is there another event listener I need to use instead of deviceready?

document.addEventListener('deviceready', () => {
  console.log('safeArea1', getSafeArea()); // Sometimes returns 34 and sometimes 0 -> bad
  setTimeout(() => console.log('safeArea2', getSafeArea()), 1000); // Always returns 34 -> good
});

function getSafeArea() {
  return +getComputedStyle(document.documentElement).getPropertyValue('--safe-area-bottom').slice(0, -2);
}

I also have the following in my <head> tag to create the CSS variable --safe-area-bottom that getSafeArea() reads:

<style>
  :root {
    --safe-area-bottom: env(safe-area-inset-bottom);
  }
</style>

(The general approach is from: https://benfrain.com/how-to-get-the-value-of-phone-notches-environment-variables-env-in-javascript-from-css/)

1 Answers

I couldn't figure out any better solution than setTimeout either. An on 'load' listener worked only part of the time, but in case that doesn't work, I decided to recompute the value multiple times in 2^n time. This way we ensure we get the value nearly as soon as it is available, but we only have to do so 13 times to cover 8 seconds of waiting.

window.addEventListener('load', () => {
  computeValue()
})

// Sometimes that doesn't work. So for the next 8 seconds we will recompute the value
for (let i = 0; i < 13; i++) {
  setTimeout(() => {
    computeValue()
  }, 2 ** i)
}

This has worked well for me and is the next best solution to getting the value in an event listener of some kind.

Related