Ios webview with capacitor, set safe areas
Asked Answered
P

3

13

Using capacitor to build an app in ios. In ios the webview covers the whole screen, for iphone-x that means the notch will be included and content will go behind it, like the picture on the right. But i want the picture on the left, black bars on 'no go areas'.

ex

The expected solution (html/css) for this would be to set correct viewport and use the 'safe-area'insert-?', se: https://css-tricks.com/the-notch-and-css/ But for the webview in ios the 'safe-area'insert' will always be 0, that is how it works => this solution is useless.

How can i solve this? Can i change the webview to not cover the whole screen, without changing in the capacitor-framework?

Perspiratory answered 2/8, 2019 at 15:58 Comment(2)
I did solve this in a dirty way, checking the screen width / heigt (window.innerWidth / window.innerHeight) and applying padding. Intresting width x heights: 375x812, 414x896, 414x736, 375x667.Perspiratory
Did you ever find a solution for this? Looks like lots of people have the same question!Vair
O
1

There is a CSS variable preset by capacitor you can use to set the padding or a margin for example.

html {
    --ion-safe-area-top: env(safe-area-inset-top);
    --ion-safe-area-bottom: env(safe-area-inset-bottom);
    --ion-safe-area-left: env(safe-area-inset-left);
    --ion-safe-area-right: env(safe-area-inset-right);
}
Ozonosphere answered 15/9, 2020 at 8:46 Comment(0)
H
1

You can use a compatible Cordova plugin cordova-plugin-safearea

npm i -D cordova-plugin-safearea
npx cap sync

With this installed, you can request the safe margin area over the cordova/capacitor bridge:

// Types for clarity
type SafeArea = {
  top: string,
  bottom: string,
}

window.plugins.safearea.get(
  (result: SafeArea) => {
    // elegantly set the result somewhere in app state
  },
  (error: any) => {
    // maybe set some sensible fallbacks?
  }
);

You could use these values to specify extra padding on the body, or on your header / bottom-menu components

The docs say it returns the values as Numbers, but it seems to me they are actually strings (consider parseFloat before doing math with them).


I have just implemented this in React (running the getter in React.useLayoutEffect); the project is wrapped in Capacitor and have tested on two iOS devices with different ingenious Apple notch screen formats (iPhone 8 and iPhone 11 Pro).

Refer to the documentation for more at https://github.com/rickgbw/cordova-plugin-safearea

Hearthstone answered 13/5, 2021 at 2:28 Comment(0)
S
1

I think you can just set the safe area like this like in any normal website using the env() mechanism:

body {
    /* Other styles above... */
    padding: env(safe-area-inset-top) env(safe-area-inset-right) env(safe-area-inset-bottom) env(safe-area-inset-left);
}

(I'm using a plain Capacitor app without Ionic.)

Signboard answered 29/10, 2023 at 12:25 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.