Skip to content
Advertisement

How to get current screen orientation in iOS Safari?

I am trying to get the current screen orientation of iOS however my function which work on chrome dev tool emulator and desktop but it doesn’t work on iOS.

Here is my function:

export type ScreenOrientation = "landscape" | "portrait";

export function getScreenOrientation(): ScreenOrientation
{
  if (window.screen.availHeight > window.screen.availWidth)
    return "portrait";
  else
    return "landscape";
}

and here is how my program rougthly do to detect the screen orientation change and to use the function:

  import { getScreenOrientation } from "../../Utils/getOrientation";
  const shoWPortraitModeError = getScreenOrientation() == "landscape" ? false : true;
  window.onorientationchange = function () {
    const newState = getScreenOrientation() == "landscape" ? false : true;
    console.log("window.onorientationchange: ", newState)
    shoWPortraitModeError  = newState;
  };

I tried using window.screen.height and window.screen.width however it didn’t worked. Here is the function:

export type ScreenOrientation = "landscape" | "portrait";

export function getScreenOrientation(): ScreenOrientation
{
  if (window.screen.availHeight > window.screen.availWidth)
    return "portrait";
  else
    return "landscape";
}

I launch the iOS safari debugger on a mac vm and I noticed that the window.screen value doesn’t changes when I turn the screen: thing i noticed

It made me wonder what are the different property I can use to detect the screen orientation on ios ?

Advertisement

Answer

If you want to do some CSS, you can use media queries.

https://developer.mozilla.org/en-US/docs/Web/CSS/@media/orientation

Basically you can use @media (orientation: landscape) {}

If you want it in JS, for other purposes, you can use:

let orientation = (screen.orientation || {}).type || screen.mozOrientation || screen.msOrientation;

if (orientation === "landscape-primary") {
  console.log("That looks good.");
} else if (orientation === "landscape-secondary") {
  console.log("Mmmh... the screen is upside down!");
} else if (orientation === "portrait-secondary" || orientation === "portrait-primary") {
  console.log("Mmmh... you should rotate your device to landscape");
} else if (orientation === undefined) {
  console.log("The orientation API isn't supported in this browser :(");
}
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement