Android webview javascript not working on API 18 or higher

余生颓废 提交于 2019-12-13 10:32:06

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!