Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to retrieve the full viewport height on iOS Safari via JS?

I would like to retrieve the full height of the viewport on iOS Safari via JavaScript. window.innerHeight is unreliable because it changes as the UI contracts. On my iPhone 12, the following is reported:

  • When the page loads, window.innerHeight is 664px.
  • As I scroll, window.innerHeight is increased (eg. 707px).
  • Once the UI has fully contracted, window.innerHeight is consistently 745px.

In CSS, 100vh gives me the full height of the viewport when the page loads. Thus I can insert an element to manually measure it:

let d = document.createElement('div');
d.style.position = 'absolute';
d.style.width = '1px';
d.style.height = '100vh';
document.body.prepend(d);
dh = d.clientHeight; // 745px

Is it possible to get the value of 100vh in pixels without inserting an element? There are new CSS units that accomodate for the changes to the viewport but I'm not sure if there are equivalents in JS.

Thanks for your time and apologies if this is a duplicate question, I could not find it asked before.

like image 291
SalutBarbu Avatar asked Oct 18 '25 15:10

SalutBarbu


2 Answers

I don't think there's a property of window that corresponds to the new dvh (Display Viewport Height) CSS unit.

From a practical standpoint, I wanted to set my (dynamically-created) <canvas> to 100dvh via JS when the page loads. This ensures that when the user scrolls on iOS Safari and the browser chrome is hidden, the canvas is already the full height of the window. Before scrolling, window.innerHeight only gives the equivalent of 100vh, not 100dvh.

My solution was simply to insert the <canvas> in the html and set the height to 100dvh with CSS, then read the dimensions of the element (el.clientHeight) back.

like image 143
SalutBarbu Avatar answered Oct 20 '25 05:10

SalutBarbu


A possible way to get what you are wanting to achieve would be to still use window.innerHeight but use a function and a setInterval to constantly retrieve the value. Maybe something like this would work for you:

here's a jsfliddle that you can play around with the viewport screen size and see it change. https://jsfiddle.net/59vyemjt/

var heightjs = function(){
let x = window.innerHeight;
document.getElementById('test').innerHTML= x;
}

setInterval(heightjs, 50);
<div id="test"></div>
like image 28
John Avatar answered Oct 20 '25 05:10

John