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/)