Visual viewport detection in Firefox mobile browser

蓝咒 提交于 2019-12-08 02:36:29

I had the same problem and came up with the following solution:

Place a zero-pixel size "dummy" div in the bottom right corner of the screen (using "position:fixed") and query its position via getBoundingClientRect().left/top, which gives the width/height of the visual viewport.

Example code (querying only the width):

<div id="dummy" style="position:fixed;right:0;bottom:0"></div>
<button onclick="alert(
    'innerWidth: ' + window.innerWidth + ' / ' + 
    document.getElementById('dummy').getBoundingClientRect().left
);">Test</button>

Loading the above web page in a browser and pressing the "Test" button will display the viewport widths as queried via the window.innerWidth and the getBoundingClientRect() methods.

  1. On desktop Firefox, both methods yield the width of the visual viewport in CSS pixels, which depends on the window width and zoom level.

  2. On mobile Firefox, window.innerWidth gives the width of the layout viewport (which is independent of zoom level, and pretty much useless for our purpose). On the contrary, the getBoundingClientRect() method does indeed yield the current width of the visual viewport in CSS pixels.

Tested on Desktop FF ver 19.0.2 and on Firefox mobile ver 24.0.

window.innerWidth window.innerHeight

these two work for all browsers

This is easy with jQuery.documentSize (which I wrote). You can query the size of the layout viewport and the size of the visual viewport with it. It also handles the bug which affects the innerWidth, innerHeight implementations in older versions of Firefox.

Despite the name, it is written in vanilla Javascript, and you can use it without jQuery, too.

visualWidth = $.windowWidth( { viewport: "visual" } );
layoutWidth = $.windowWidth( { viewport: "layout" } );

Likewise for height.

(This question is really old, and the participants probably won't care, but at least it has prompted me to test jQuery.documentSize with Firefox for Android, which I hadn't done yet. Works as expected.)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!