Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 559
Vicky Avatar asked Mar 10 '11 19:03

Vicky


People also ask

What does JavaScript function return by default?

A function without a return statement will return a default value. In the case of a constructor called with the new keyword, the default value is the value of its this parameter. For all other functions, the default return value is undefined .

What is $() JavaScript?

The $() function The dollar function, $(), can be used as shorthand for the getElementById function. To refer to an element in the Document Object Model (DOM) of an HTML page, the usual function identifying an element is: document.

Can I pass this in JavaScript?

"Can I pass “this” as a parameter to another function in javascript" --- yes you can, it is an ordinary variable with a reference to current object. Any issues with that?


1 Answers

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

like image 71
Umair A. Avatar answered Sep 20 '22 11:09

Umair A.