Note that there are some explanatory texts on larger screens.

plurals
  1. POPassing JavaScript anonymous function as parameter to WebView
    text
    copied!<p>I have a Native application, which has a WebView in it. I add a class to the WebView to be able to call it from JavaScript like so:</p> <pre><code>webView.addJavascriptInterface(new JavascriptInterface(webView, handler), "Android.JSI"); </code></pre> <p>I then call the JavaScriptInterface class from JavaScript. My HTML/JavaScript looks like:</p> <pre><code>&lt;input type="button" value="Sleep Alert" onclick="sleepAlert(sleepAlertCallbackSuccess, sleepAlertCallbackFail, 'Hi Sleep Alert');" /&gt; function sleepAlert(callBackSuccess, callBackFailure, message) { window.Android.JSI.sleepAlert(callBackSuccess.name, callBackFailure.name, message); } function sleepAlertCallbackSuccess(message) { alert("success: " + message); } function sleepAlertCallbackFail(message) { alert("fail: " + message); } </code></pre> <p>I then callback into the JavaScript like so:</p> <pre><code>js = "javascript:" + callbackSuccess + "('" + message + "')"; webView.loadUrl(js); </code></pre> <p>This works, but I am kind of stuck on if the user wants to pass in an anonymous function instead of a normal named function. I.E.</p> <pre><code>&lt;input type="button" value="Anonymous call back" onclick="sleepAlert(function(message) { alert(message); }, sleepAlertCallbackFail, 'anonymous sleep alert');" /&gt; </code></pre> <p>When I pass this in to my Java class</p> <pre><code>public void sleepAlert(final String callbackSuccess, String callbackFail, final String message) </code></pre> <p>It says callbackSuccess is undefined.</p> <p>Any ideas on the proper way to do this as I feel im getting lost going the wrong way?</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload