简体   繁体   中英

How do I pass return values from a javascript function to android?

I want to let my android app call a function written in javascript and expect a return value from that.

I understand that WebView.loadUrl works asynchronously, so what I am doing now is to let javascript notify my android app when it is done and pass in the return value by calling a java function using javascriptinterface .

I wonder if there are better ways of doing this and whether anyone has noticed any message loss between javascript and android.

I just got your problem.

Have a JS function like this.

function androidResponse() {
   window.cpjs.sendToAndroid("I am being sent to Android.");
}

Set up Android (Java).

Have a final class like this

final class IJavascriptHandler {
   IJavascriptHandler() {
   }

   // This annotation is required in Jelly Bean and later:
   @JavascriptInterface
   public void sendToAndroid(String text) {
      // this is called from JS with passed value
      Toast t = Toast.makeText(getApplicationContext(), text, 2000);
      t.show();
   }
}

Then on your WebView load have.

webView.addJavascriptInterface(new IJavascriptHandler(), "cpjs");

Call JS function

webView.loadUrl("javascript:androidResponse();void(0)");

UPDATED


Also I had a very bad time experiencing problems while passing hundreds of lines of string to JS from Java and I have subsequent post on StackOverflow with no good answers but finally resolved it knowing problme was of special characters inside string so take of special characters when you use string passing to and fro.

Passing Data From Javascript To Android WebView

HTML String Inside Nested String

HTML TextArea Characters Limit Inside Android WebView

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM