Search code examples
javascriptandroidandroid-webviewandroid-4.4-kitkat

How to run javascript in Android KitKat WebView?


I have following code in my WebView

<script src="remote src" param1="value1" param2="value2" ... />;

When it runs on Androids, lower than Kitkat, I use typical

webView.loadDataWithBaseURL(..)

and script works fine. But, as we know, in KitKat WebView had absolutely changed, and scripts should be run as

webView.evaluateJavascript(script, callback);

and now is very unclear how to run my script, which is rendered with the rest of the page, in KitKat.


Solution

  • How about this:

    String jScript = "(function() {\n" +
                        "var p=document.getElementsByTagName('head')[0];\n" +
                        "var s=document.createElement(\"script\");\n" +
                        "s.type=\"text/javascript\";\n" +
                        "s.src=\"http://pathtoscript/jscript.js\";\n" +
                        "s.async = true;\n" +
                        "p.appendChild(s);\n" +
                    "}\n" +
                "})();\n";
    
    webView.evaluateJavascript(jScript, callback);
    

    But in this case i don't know is there possibility to get a callback.