Load Javascripts to Webview Android Kitkat

Asked

Viewed 361 times

3

I have a native app with Webview where I upload a set of pages with a ViewPager.

For each Page I create an instance with Webview loading an html via loadDataWithBaseURL.

As I depend on some Avascripts on the pages, I load like this view.loadUrl("javascript:" + myJavaScriptFile) at the event onPageStarted of my subclass of WebViewClient.

That way every time an html is loaded at the beginning I already load my Avascripts.

Summing up the prose I have basically the Reader.

Everything is working in versions 4.x while mine sdkTargetVersion = 14. But when did I put sdkTargetVersion = 19 (Kitkat) stopped working all my crypts.

I’ve done everything on this link Migrating to Webview in Android 4.4

Does anyone have any ideas to help me?

2 answers

4

Try this:

String jsMethod = "doSomething()";

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
    webview.evaluateJavascript(jsMethod, null);
} else {
    webview.loadUrl("javascript:" + jsMethod);
}

3


From API 19 the method loadUrl, does not run more script and should only be used for URL’s.

For this purpose was added to the Webview the method public void evaluateJavascript (String script, ValueCallback<String> resultCallback).

So to make things more transparent, I created a Webview de Support, that already treats this situation, follows code of my solution:

public class WebViewSupport extends WebView {

    public WebViewSupport(Context context) {
        super(context);
    }

    public WebViewSupport(Context context, AttributeSet set) {
        super(context, set);
    }

    @TargetApi(Build.VERSION_CODES.KITKAT)
    @Override
    public void loadUrl(String url) {
        if (url.startsWith("javascript:")) {
            if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT) {
                String script = url.split("javascript:")[1];
                Log.i("WebViewSupport", "Script: " + script);
                evaluateJavascript(script, null);
                return;
            }
        }
        super.loadUrl(url);
    }
}

My solution uses the same concept cited by Eduardo Oliveira in his reply.

Then you just need to call loadUrl, in the same way that it called for older versions of Android, thus keeping the same code between versions. Something similar to this, for example:

String jsMethod = "doSomething()";    
webViewSupportInstance.loadUrl("javascript:" + jsMethod);
  • 1

    Thank you very much, even already using the form of our colleague Eduardo, this your scheme works very well and elegant!! Vlw..

Browser other questions tagged

You are not signed in. Login or sign up in order to post.