Reputation: 173662
Background
I'm having trouble getting a reliable viewport size using JavaScript. I've read through this guide to set up the application and this guide to learn about targeting specific device resolutions.
This is the <meta>
tag on the page:
<!DOCTYPE html>
...
<meta name="viewport" content="target-densitydpi=device-dpi" />
This allows me to use the sharpest images to draw the interface. To test the resolution I've written this piece of code:
window.addEventListener('orientationchange', function() {
console.log(screen.availWidth + ' x ' + screen.availHeight)
}
// 1080 x 1920 or 1920 x 1080
Problem 1
I had hoped the actual available pixels could be calculated like:
width := screen.availWidth / devicePixelRatio
height := screen.availHeight / devicePixelRatio
But the devicePixelRatio
is fixed at 3
, independent of the target dpi; so how can I determine the actual pixels at my disposal?
Problem 2
The above screen.availHeight
is not accurate because it doesn't take into account the actual height of the WebView
component.
I've tried these alternatives:
console.log(document.documentElement.offsetHeight);
// 1920
console.log(window.innerHeight);
// 240
These values are pretty much useless, and worse, they don't change when the screen rotates nor are they dependent on the target dpi. Is there a better way to do this?
Upvotes: 5
Views: 2223
Reputation: 4676
Can you use CSS media queries to target what you want to target?
If so, maybe you can solve your problem with matchMedia.js -- a cross-browser solution for testing media queries in JavaScript. Something to consider, right? Since you would have, in addition to size queries, -webkit-device-pixel-ratio
at your disposal (mentioned in that guide you linked to)?
Upvotes: 0
Reputation: 27040
It's been quite awhile since I last worked with the android SDK and web views, but can't you simply expose the information from the java side where you can determine it reliably? So any time your orientation changes + initially you call
webview.loadUrl("javascript:setResolution(x,y,orientation)");
and in your javascript you write the dimensions to a logical place.
It's not btw that this would be impossible from javascript, but any time I need to do anything remotely along the lines of what you want to do it takes a lot of trial and error to get it cross device supported, so personally I would advice you to use the fact that you have a webview to your advantage. (And if you are by any chance using a webview framework like cordova you can even relatively simply make a javascript plugin out of it)
Upvotes: 3