javascripthtmlcssgoogle-chromeandroid-chrome

Get Android Chrome Browser Address bar height in JS


How do I get the height of the address bar in JavaScript in the Chrome browser for Android (marked by red rectangle in left picture)? I need to know that as it disappears while scrolling down and I need to react to that because the viewport height is different then.

enter image description here

One solution I already figured out:

  1. Get viewport height at initial state: var height = Math.max(document.documentElement.clientHeight, window.innerHeight || 0);

  2. Get viewport height when the address bar has disappeared

  3. Compute difference between both values

Problem is that you have to be in the second state to know that.


Solution

  • Best approach for me was to have something like that:

    $(document).ready(function(){   
    
    var viewportHeight = Math.max(document.documentElement.clientHeight, window.innerHeight || 0);
    var viewportWidth = Math.max(document.documentElement.clientWidth, window.innerWidth || 0);
    var isPortrait = viewportHeight > viewportWidth;
    
    $( window ).resize(onresize);
    
    function onresize() {
            var newViewportHeight = Math.max(document.documentElement.clientHeight, window.innerHeight || 0);
            var newViewportWidth = Math.max(document.documentElement.clientWidth, window.innerWidth || 0);
            var hasOrientationChanged = (newViewportHeight > newViewportWidth) != isPortrait;
            var addressbarHeight = 130;
    
            if (!hasOrientationChanged && (newViewportHeight != viewportHeight)) {
                addressbarHeight = Math.abs(newViewportHeight - viewportHeight);
                if (newViewportHeight < viewportHeight) {
                    // Android Chrome address bar has appeared
                } else {
                    // Android Chrome address bar has disappeared
                }
            } else if(hasOrientationChanged) {
                // Orientation change
            }
    
            viewportHeight = newViewportHeight;
            viewportWidth = newViewportWidth;
            isPortrait = viewportHeight > viewportWidth;
    }
    });