6

I'm trying to add more empty space to a loaded WebView using JavaScript.

I load data using loadDataWithBaseUrl() from a String resource. Then, after measuring some content, I need to make WebView bigger, say for 100 pixels. So I call javascript function using loadDataWithBaseUrl():

mWebView.loadUrl("javascript:addHeight()");

Javascript function is defined in the original HTML:

function addHeight() { " +
    var elemDiv = document.createElement('div');
    elemDiv.style.cssText = 'height:100px;'; 
    document.body.appendChild(elemDiv); 
} 

After this, WebView resizes itself to fit the new content. However, resulting height is not originalSize + 100px, but bigger. I don't know where's the problem. I can't determine the target size, because it depends on the size of the appended div and it will be always different.

Has anybody tried this? Are you familiar with this behaviour?

camelCaseCoder
  • 1,447
  • 19
  • 32
Hawk
  • 392
  • 4
  • 24
  • Possible duplicate of [How to Shrink WebView size dynamically according to its content?](http://stackoverflow.com/questions/15546416/how-to-shrink-webview-size-dynamically-according-to-its-content) – e4c5 Oct 01 '15 at 03:25
  • By "resulting height", do you mean the height of WebView view element (on the Android side), or the page dimensions, as reported by `window.innerHeight` or `window.outerHeight` in your JavaScript code? – Mikhail Naganov Oct 05 '15 at 19:14
  • this is not a clear question , please show your javascript addHeight() code. – ProllyGeek Oct 09 '15 at 21:04

1 Answers1

2

I found the next solution. There used JS callback. I hope this helps you. This change in size should work better than dynamic.

    private void setupWebView() {
    webView.getSettings().setJavaScriptEnabled(true);
    webView.setWebViewClient(new WebViewClient() {
        @Override
        public void onPageFinished(WebView view, String url) {
            webView.loadUrl("javascript:MyApp.resize(document.body.getBoundingClientRect().height)");
            super.onPageFinished(view, url);
        }
    });
    webView.addJavascriptInterface(this, "MyApp");
}
@JavascriptInterface
public void resize(final float height) {
    MyActivity.this.runOnUiThread(new Runnable() {
        @Override
        public void run() {
            webView.setLayoutParams(new LinearLayout.LayoutParams(getResources().getDisplayMetrics().widthPixels, (int) (height * getResources().getDisplayMetrics().density)));
        }
    });
}

And of see paragraph 4 of this list. Good luck!

Community
  • 1
  • 1
user2413972
  • 1,355
  • 2
  • 9
  • 25
  • 2
    Using Android 5.1.1, nothing seems to happen - setting LayoutParams doesn't change the WebView at all. – Hawk Oct 03 '15 at 08:26