$ cat tips/visualviewport-chrome-android-keyboard.md

Chrome on Android: visualViewport.height is too tall by the address bar when the keyboard opens

When the keyboard opens while the address bar is tucked away, Chrome brings the bar back but keeps the layout height as if the bar were gone, and visualViewport.height comes out too tall by the bar. Remember the shortest window.innerHeight and take the difference off while the keyboard is up.

var shortest = window.innerHeight;
var width = window.innerWidth;
window.addEventListener("resize", function () {
  if (window.innerWidth !== width) {
    width = window.innerWidth;
    shortest = window.innerHeight;
  }
  shortest = Math.min(shortest, window.innerHeight);
});

function visibleHeight() {
  var vv = window.visualViewport;
  var keyboard = Math.max(0, window.innerHeight - vv.height);
  var bar = keyboard > 0 ? Math.max(0, window.innerHeight - shortest) : 0;
  return vv.height - bar;
}

The shortest window.innerHeight seen at a given width is the height with the address bar showing. Whatever the current height exceeds it by is the bar. A browser that keeps its numbers straight gives zero here, so the correction breaks nothing.

How to reproduce: scroll the page down so the address bar hides, then tap a text field. An element pinned to the bottom of the visible area then slides under the keyboard by the height of the address bar, 56 px on a Pixel 9 Pro.

You can connect to the phone without a cable, over Wi-Fi adb.

checked: Pixel 9 Pro, Chrome on Android (address bar 56 px)

$ ls ./blog/tips
all tips →
↑