title: Javascript Callback function pass to Android
body: <p>I have a javascript interface implemented in Java that is called by my javascript code that is loaded in the webview.</p>
  
  <p>JS Inside webview:</p>
  
  <pre><code>Android.myFunction(function(data){
      console.log(data);
  });
  </code></pre>
  
  <p>Java:</p>
  
  <pre><code>public class JavaScriptInterface {
  
      Context context;
      WebView webView;
  
      JavaScriptInterface(Context c, WebView w) {
          context = c;
          webView = w;
      }
  
      public void myFunction(String callback) {
          //when I log callback, it is "undefined"
           String someData = "Yay for data";
           String js =
               "javascript:(function() { "
                   + "var callback = " + callback + ";"
                   + "callback('" + someData + "');"
               + "})()";
          webView.loadUrl(js);
      }
  }
  </code></pre>
  
  <p>The string that gets loaded by webview ends up being:</p>
  
  <pre><code>javascript:(function() {var callback = undefined; undefined();})()
  </code></pre>
  
  <p>I have a few ideas:</p>
  
  <p>a.  Build the callback in JS as a string.</p>
  
  <p>b.  Call the callback's toString() before passing it to Android.myFunction();</p>
  
  <p>My question is, what is the best way to do this?  I would love to be able to just pass objects over to Android and it magically works out.  Obviously, this isn't the case. ;)  What is the next best way to do it?</p>