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?
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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With