Sometimes, we may want to detect page zoom levels in modern browsers.
In this article, we’ll look at how to detect zoom levels in modern browsers.
Using the window.devicePixelRatio Property
One way to detect the browser zoom level is to use the window.devicePixelRatio
property.
For instance, we can write:
window.addEventListener('resize', () => {
const browserZoomLevel = Math.round(window.devicePixelRatio * 100);
console.log(browserZoomLevel)
})
When we zoom in or out, the resize
event will be triggered.
So we can listen to it with addEventListener
.
In the event handler callback, we get the window.devicePixelRatio
which has the ratio between the current pixel size and the regular pixel size.
Divide outerWidth by innerWidth
Since outerWidth
is measured in screen pixels and innerWidth
is measured in CSS pixels, we can use that to use the ratio between them to determine the zoom level.
For instance, we can write:
window.addEventListener('resize', () => {
const browserZoomLevel = (window.outerWidth - 8) / window.innerWidth;
console.log(browserZoomLevel)
})
Then browserZoomLevel
is proportional to how much we zoom in or out.
Conclusion
We can detect page zoom levels with the window.devicePixelRatio
property or the ratio between the outerWidth
and innerWidth
.
4 replies on “How to Detect Page Zoom Levels in Modern Browsers?”
What happen when the devtools is open?
It should work the same way.
This does not work on displays with a high pixel density. Especially on MacBooks with Retina display. Sadly there doesn’t seem to be any other solution.
The problem starts when some decices may shiw different devicePixelRatuo.
For example, on a regular screen and on a retina displays the pixel ratio is different.