How to Get true pixel height and width of window in javascript

By | May 26, 2023

If you check the window outerwidth on a maximised browser window, you should get the resolution width of your screen or display in general. For example when I run the following code (in console) in Firefox I get 1920px which is my resolution width:

window.outerWidth
1920

On Google Chrome however, the reported dimension is different and does not match the previous value.

window.outerWidth
1756

Clearly Chrome does not show the true pixel dimensions when using attributes like outerWidth and the likes.

window.outerWidth gets the width of the outside of the browser window. It represents the width of the whole browser window including sidebar (if expanded), window chrome and window resizing borders/handles.

It seems that the units are different than hardware pixels.

Difference shows up, with all other metrics like window.innerHeight, window.outerHeight, window.innerWidth. Not just the window element, but all html elements on the page are measured in this different unit, which keeps things consistent.

It confused me quite a lot and took nearly an entire day to figure out the real reason, which turned out to be the system's DPI setting.

Now Google Chrome takes into account the system dpi setting and scales the dimensions of browser elements accordingly.
But Firefox does not seem to do it.

The solution!

Now most of the time this "non-real" measurement of dimensions in chrome should not affect any kind of user-interface code inside javascript.

However, if you still want to measure the dimension of something on the page in real pixels the solution is to use the value of window.devicePixelRatio

Chrome Fixed:

window.devicePixelRatio * window.outerWidth
1920.625

Now we get the real width in pixel of a maximised browser. But this is still not perfect as there is an in-accurate trailing decimal part to the dimension.

About Silver Moon

A Tech Enthusiast, Blogger, Linux Fan and a Software Developer. Writes about Computer hardware, Linux and Open Source software and coding in Python, Php and Javascript. He can be reached at [email protected].

Leave a Reply

Your email address will not be published. Required fields are marked *