Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

calling window.innerHeight upon window resize event doesn't give correct height

I am using window.onresize to listen for viewport size changes so I can scale my content appropriately (It's a game UI, so it seems easiest to use window.onresize + css scale, other suggestions are welcome).

However, on certain browsers, calling window.innerHeight or window.innerWidth right after the onresize is fired gives the wrong result.

Here is a minimal working example:

<html>
  <head>
    <title>Firefox Resize bug</title>
    <link
      rel="manifest"
      href='data:application/manifest+json,{ "name": "onresize bug", "display":"standalone"}'
    />
  </head>
  <body>
    Height: <span id="heightField"></span>
    <br />
    Width: <span id="widthField"></span>
    <script>
      const heightField = document.getElementById("heightField");
      const widthField = document.getElementById("widthField");
      const updateSize = () => {
        heightField.textContent = window.innerHeight;
        widthField.textContent = window.innerWidth;
      };
      window.onresize = updateSize;
      updateSize();
    </script>
  </body>
</html>

This works fine in iOS 12 Safari, when you change the orientation, the height and width update correctly.

However, it does not work on iOS Firefox/Chrome (at least, not reliably), and it does not work if you add this app to the home screen on an iPhone (see the manifest in the example above)

I've been getting around this by firing my updateSize 500ms after a onresize event, but what's really going on here?

like image 452
Antti S. Avatar asked Nov 24 '25 02:11

Antti S.


1 Answers

It's a bug in webkit.

https://bugs.webkit.org/show_bug.cgi?id=185886

In iOS, the window.onresize event fires in a WKWebView when the device switches orientation. However, if the WKWebView is positioned WITH Auto Layout, window.innerWidth and window.innerHeight will report incorrect values from within the window.onresize event handler. But, if the WKWebView is positioned manually WITHOUT using Auto Layout, window.innerWidth and window.innerHeight will report correct values in the event handler.

like image 120
Antti S. Avatar answered Nov 25 '25 17:11

Antti S.