Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WebView returns bad window.innerHeight

I have an application that makes use of the Android WebView, as well as some JavaScript. When my WebViewClient calls onPageFinished(), I alert my JavaScript to run an initializing method. My JavaScript is enabled and loaded before I hit onPageFinished().

In that JavaScript method I make use of window.innerWidth. However, the value it returns is always wrong and always the same. Regardless of my orientation it reports that the inner width is 320, and the inner height is 240. (Correct width values for portrait and landscape are 360 and 598 respectively.) Anywhere else I access window.innerWidth or window.innerHeight in JavaScript it gives me an accurate number.

What is more puzzling is that if I check the height or width of the WebView directly in my onPageFinished() call using

int height = view.getHeight();

int width = view.getWidth();

then it always returns correctly (although it returns the exact pixel numbers, not the DIP). This makes me think that everything has finished loading with the WebView and so I shouldn't have any problems in my JavaScript.

Any ideas as to what is going on?

Thanks in advance!

like image 431
Jon Avatar asked Sep 06 '12 16:09

Jon


1 Answers

This is because Javascript executes before WebView's View related initialization. And Android WebView returns a 320x240 default value to JS. Execute your JS after some time is ok, like this

function go() {
int height = view.getHeight();
int width = view.getWidth();
};
window.setTimeout(go, 300);
like image 79
carltao Avatar answered Oct 06 '22 10:10

carltao