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:
webView.addJavascriptInterface(new JavascriptInterface(webView, handler), "Android.JSI");
I then call the JavaScriptInterface class from JavaScript. My HTML/JavaScript looks like:
<input type="button" value="Sleep Alert" onclick="sleepAlert(sleepAlertCallbackSuccess, sleepAlertCallbackFail, 'Hi Sleep Alert');" />
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);
}
I then callback into the JavaScript like so:
js = "javascript:" + callbackSuccess + "('" + message + "')";
webView.loadUrl(js);
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.
<input type="button" value="Anonymous call back" onclick="sleepAlert(function(message) { alert(message); }, sleepAlertCallbackFail, 'anonymous sleep alert');" />
When I pass this in to my Java class
public void sleepAlert(final String callbackSuccess, String callbackFail, final String message)
It says callbackSuccess is undefined.
Any ideas on the proper way to do this as I feel im getting lost going the wrong way?
Set it to a variable. You can do something like:
Then if it’s a method it’ll resolve to:
or if it’s anonymous:
Since you’re passing it in the location bar, you’ll have to URI encode it, etc. but the approach should work.
Update:
Here’s something like what I mean:
Now you can give it something like “function(message) { alert(message); }” and it’ll work. I’d be pretty careful about letting the user run arbitrary code here by the way. Hard to say without seeing more, but this kind of thing can risk exposing security holes fairly easily.