In 2022, almost browsers still block the behavior of customization the browser zoom level from code (as I read somewhere, it is stated to be a bad practice and it should be controlled by the user, not the web itself).
Although, we still can handle this by a small "hack", which just effect the view (look & feel), not changing the real browser zoom level. It may also break your layout in some situations (if responsiveness available).
In my case, I need to force the screen always in 100% (default browser zoom level) on page load, even though last time user visited the web they changed it to any other values.
I found another topic on how to detect browser zoom level, combined with
Vinod's answer above, the value of zooming (in/out) is result of (100 / browserZoomLevel) * 100
.
const handleZoom = () => {
const browserZoomLevel = Math.round(window.devicePixelRatio * 100)
document.body.style.zoom = `${100 / browserZoomLevel * 100}%`
}
// call handleZoom() in the place you want
or a shorter version
const handleZoom = () => {
document.body.style.zoom = `${Math.round(100 / window.devicePixelRatio)}%`
}
Now pretty much browsers supports window.devicePixelRatio
. However, the ratio maybe different on high DPI/retina displays (read more here).
Hope this help!
I'm sorry for any inconvenience due to my English.