javascriptandroidwebviewwebviewclient

Android webview javascript not working on API 18 or higher


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


Solution

  • 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: