Skip to content Skip to sidebar Skip to footer

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 somet

Solution 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!';})()");

Solution 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

Post a Comment for "Android Webview Javascript Not Working On Api 18 Or Higher"