问题
I want to display a website in WebView
with manipulating some DOM element. I mean, I want to remove a special div element or replace it with something.
For this purpose I did something like this:
For replacing something I use this model
document.getElementById("demo").innerHTML = "Hello World!";
I apply it for Android WebView
like this:
public class WebClient extends WebViewClient {
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
@Override
public void onPageFinished(WebView view, final String url) {
view.loadUrl("javascript:document.getElementById(\"jumbotron-company\").innerHTML = \"\";");
}
}
It is work on my device which API is 18 but not working on emulators or device which have API greater than 18
回答1:
What @Mattia said is correct. Use evaluateJavascript
if possible. It has another advantage of being able to return the value of the result back from JavaScript.
But if you want an API-agnostic workaround, make sure that the code you evaluate using loadUrl("javascript:...")
just doesn't produce any return value. An assignment returns the assigned value. In newer versions of WebView this value is used as contents for a new page that replaces the existing one.
You can make sure that the expression you are evaluating doesn't produce a return value in two ways:
append
void(0);
statement at the end, e.g.loadUrl("javascript:elt.innerHTML='Hello World!';void(0);");
run your code inside a function that doesn't return a value, e.g.
loadUrl("(function(){elt.innerHTML='Hello World!';})()");
回答2:
From API level 19 you should use evaluateJavascript:
public void evaluateJavascript (String script, ValueCallback resultCallback)
Added in API level 19 Asynchronously evaluates JavaScript in the context of the currently displayed page. If non-null, |resultCallback| will be invoked with any result returned from that execution. This method must be called on the UI thread and the callback will be made on the UI thread.
Please refer to migration guide for WebView in Android 4.4: http://developer.android.com/guide/webapps/migrating.html
来源:https://stackoverflow.com/questions/30360889/android-webview-javascript-not-working-on-api-18-or-higher