How to detect page zoom level in all modern browsers?

后端 未结 28 2268
慢半拍i
慢半拍i 2020-11-21 05:27
  1. How can I detect the page zoom level in all modern browsers? While this thread tells how to do it in IE7 and IE8, I can\'t find a good cross-browser solution.

28条回答
  •  深忆病人
    2020-11-21 06:06

    This answer is based on comments about devicePixelRatio coming back incorrectly on user1080381's answer.

    I found that this command was coming back incorrectly in some instances too when working with a desktop, Surface Pro 3, and Surface Pro 4.

    What I found is that it worked on my desktop, but the SP3 and SP4 were giving different numbers from each other and the desktop.

    I noticed though that the SP3 was coming back as 1 and a half times the zoom level I was expecting. When I took a look at the display settings, the SP3 was actually set to 150% instead of the 100% I had on my desktop.

    So, the solution to the comments should be to divide the returned zoom level by the scale of the machine you are currently on.

    I was able to get the scale in the Windows settings by doing the following:

    ManagementObjectSearcher searcher = new ManagementObjectSearcher("SELECT * FROM Win32_DesktopMonitor");
    double deviceScale = Convert.ToDouble(searcher.Get().OfType().FirstOrDefault()["PixelsPerXLogicalInch"]);
    int standardPixelPerInch = 96;
    return deviceScale / standardPixelPerInch;
    

    So in the case of my SP3, this is how this code looks at 100% zoom:

    devicePixelRatio = 1.5
    deviceScale = 144
    deviceScale / standardPixelPerInch = 1.5
    devicePixelRatio / (deviceScale / standardPixelPerInch) = 1
    

    Multiplying by the 100 in user1080381's original answer then would give you a zoom of 100 (%).

提交回复
热议问题