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

前端 未结 1 1592
后悔当初
后悔当初 2020-12-23 23:22

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

I understand that W

1条回答
  •  囚心锁ツ
    2020-12-24 00:00

    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

    0 讨论(0)
提交回复
热议问题