How to Call JavaScript from Android

Calling JavaScript from Android

According to CW answer,

You need to wait until your page is loaded

private void helloJs(){
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT) {
webView.evaluateJavascript("javascript:hello();", null);
} else {
webView.loadUrl("javascript:hello();");
}
}

webView.setWebViewClient(new WebViewClient() {
public void onPageFinished(WebView view, String url) {
helloJs();
}
});

It is possible to call a javascript function in android?

I believe you can use

WebView webView = (WebView) findViewById(R.id.webview);
webView.setWebChromeClient(new MyCustomChromeClient(this));
webView.getSettings().setJavaScriptEnabled(true);
webView.evaluateJavascript("globalJavascriptFunction();", null);

https://developer.android.com/reference/android/webkit/WebView#evaluateJavascript(java.lang.String,%20android.webkit.ValueCallback%3Cjava.lang.String%3E)

The second argument is a callback.


[edit]

To get a value back from the javascript, you can do something like this:

webView.evaluateJavascript("globalJavascriptFunction();", new ValueCallback<String>() {
@Override
public void onReceiveValue(String result) {
// result is the return value of globalJavascriptFunction()
// you'll have to do some testing inside here to figure out exactly how result gets sent back for your usecase
}
});

Calling Javascript from service android

I created WebView object inside my service and I got my js function called successfully.

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
webView = new WebView(this);
WebSettings webSettings = webView.getSettings();
webSettings.setJavaScriptEnabled(true);

webView.setWebContentsDebuggingEnabled(true);
webView.setWebViewClient(
new WebViewClient() {
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);

for(int i=0; i<10; i++) {
webView.loadUrl("javascript:sample()");
}

}
}
);
webView.loadUrl("file:///android_asset/html/index.html");
return START_NOT_STICKY;
}

How to call javascript from Android?

There is a hack:

  1. Bind some Java object so that it can be called from Javascript with WebView:

    addJavascriptInterface(javaObjectCallback, "JavaCallback")
  2. Force execute javascript within an existing page by

    WebView.loadUrl("javascript: var result = window.YourJSLibrary.callSomeFunction();
    window.JavaCallback.returnResult(result)");

(in this case your java class JavaObjectCallback should have a method returnResult(..))

Note: this is a security risk - any JS code in this web page could access/call your binded Java object. Best to pass some one-time cookies to loadUrl() and pass them back your Java object to check that it's your code making the call.

How I can call javascript function and get the return value from javascript function

For API Level < 19 there are only workarounds of either using a JavascriptInterface (my preferred method, below) or else hijacking the OnJsAlert method and using the alert() dialog instead. That then means you can't use the alert() function for its intended purpose.

View:

WebView.addJavascriptInterface(new JsInterface(), "AndroidApp");
WebView.loadUrl("javascript:doStringToMyAndroid('This string from android')")

JsInterface:

public class JsInterface() {
@JavascriptInterface
void receiveString(String value) {
// String received from WebView
Log.d("MyApp", value);
}
}

Javascript:

function doStringToMyAndroid(stringFromAndroid){
var myJsString = "Hello World" + ;
// Call the JavascriptInterface instead of returning the value
window.AndroidApp.receiveString(myJsString);
}

But on API Level 19+, we now have the evaluateJavascript method:

WebView.evaluateJavascript("(function() { return getStringToMyAndroid('" + myJsString + "'); })();", new ValueCallback<String>() {
@Override
public void onReceiveValue(String s) {
Log.d("LogName", s); // Returns the value from the function
}
});

Run javascript code in Webview

From kitkat onwards use evaluateJavascript method instead loadUrl to call the javascript functions like below

    if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT) {
webView.evaluateJavascript("var FunctionOne = function () {"
+ " try{document.getElementsByClassName('test')[0].style.color='red';}catch(e){}"
+ "};", null);
} else {
webView.loadUrl("javascript:"
+ "var FunctionOne = function () {"
+ " try{document.getElementsByClassName('test')[0].style.color='red';}catch(e){}"
+ "};");
}

Enable Javascript for your webview by adding the following line

wb.getSettings().setJavaScriptEnabled(true);


Related Topics



Leave a reply



Submit