Android screen resolution in web app not constant
This is weird. I'm using javascript to figure the resolution in a web page. For that I have a following function (somewhat simplified for this purpose):
function check() {
var win = document.defaultView || document.parentWindow,
ratio = win.devicePixelRatio ? win.devicePixelRatio : 1,
h = win.innerHeight,
w = win.innerWidth,
root = document.documentElement;
if (!h) {
h = root.clientHeight;
w = root.clientWidth;
}
alert("height/width/ratio; " + h + "/" + w + "/" + ratio);
}
on android devices there seems to be a really peculiar behaviour:
I'll give a Nexus S as an example but obviously I've verified this on many other Android devices running different versions.
If you arrived to the page containing the script above by clicking on a link in an email app (gmail or outlook), the alert will yield 1130/800/1.5 (height and width are way 开发者_运维百科too high). This is consistent. Now, if you go to the address bar and edit the url (add/remove a parameter or parameter value) and hit "Go", the exact same code will yield 452/320/1.5 (thats more like it, and that's also consistent).
How and why on earth is this happening?
EDIT: worth noting is that so far this only seems to apply to devices with devicePixelRatio > 1, i.e. not older Android phones on v 1.5 / 1.6
After a lot of searching and debugging, this almost seems like a bug.
The repro is easy: if the above script is run synchronously in onload event and you click on something that opens a new window, email app or a web page with target=_blank, both screen and window width and height properties will be wrong. Makes no difference if you use jQuery, YUI or plain javascript.
The solution/workaround is to wrap the method called in onload in a setTimeout() with timeout set to 0. That will run the method asynchronously and yield correct result.
<body onload="setTimeout(check, 0);">
That, my friends, closes this case.
精彩评论