Upload JavaScripts in WebView Android KitKat

3

I have a native app with WebView where I load 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 javascripts on pages, I then load view.loadUrl("javascript:" + myJavaScriptFile) into onPageStarted event of my subclass of WebViewClient .

That way every time an html is loaded at startup I already load my javascripts.

Summarizing the prose I basically have the Reader.

Everything is working in versions 4.x while my sdkTargetVersion = 14 . But when I put sdkTargetVersion = 19 (kitkat) all the my javascripts.

I already did everything that was in this link Migrating to WebView in Android 4.4

Does anyone have an idea to help me?

    
asked by anonymous 07.08.2014 / 18:28

2 answers

3

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

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

So to make things more transparent, I created a Support WebView , which already addresses this situation , follow my solution code:

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 quoted by Eduardo Oliveira in your answer .

So you just need to call loadUrl , just as you called older versions of Android, thus keeping the same code between versions. Something similar to this, for example:

String jsMethod = "doSomething()";    
webViewSupportInstance.loadUrl("javascript:" + jsMethod);
    
15.08.2014 / 16:24
4

Try this:

String jsMethod = "doSomething()";

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