Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JS - Safari on iOS - How to get viewport scale property

On Chrome, I can get the viewport scale by looking at window.visualViewport.scale it is available on Safari, however, it seems that window.visualViewport is not defined on older versions of Safari on iOS.

Is there any workaround?

like image 620
Shlomi Schwartz Avatar asked Dec 10 '22 01:12

Shlomi Schwartz


2 Answers

Firstly, you need to get viewport width by using clientWidth or innerWidth

var viewportWidth = Math.max(document.documentElement.clientWidth, window.innerWidth || 0);

Then, you need to get actual screen width

var screenWidth = window.screen.width

Then, viewport scale is on your hand

var viewportScale = screenWidth / viewportWidth
like image 66
Vo Kim Nguyen Avatar answered Dec 24 '22 20:12

Vo Kim Nguyen


According to caniuse.com visualViewport.scale should be available in Safari for iOS from version 13.0 which was released 19 September 2019. Have you updated yet?

If you really need to support older Safari for iOS, and also if you have no need to measure scale right at the page load, you can try to catch touch events and guess/calculate scale by yourself.

If you're going to really desperate, you can try to "invent some bicycle". For example (just the concept): create and measure 2 <div> right inside <body>. One of them width: 100vw; and another width: 100%; (this actually isn't needed since blocks already will be 100% width of parent block). The trick here would be in different units. 100vw should be always 100% of the viewport, when 100% should stretch for maximum available width. Measure the difference between those 2 blocks and you can calculate scale. Be aware of those tricky margins/paddings and maybe of the landscape.

like image 43
Thomas Ashcraft Avatar answered Dec 24 '22 22:12

Thomas Ashcraft