4

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?

1 Answer 1

1

Set it to a variable. You can do something like:

var a = <whatever>; a(message);

Then if it's a method it'll resolve to:

var a = sleepAlertCallbackSuccess; a(message);

or if it's anonymous:

var a = function(message) { ... }; a(message);

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:

js = "javascript: var a=" + callbackSuccess + ";a(message);";
String url = "javascript:" + Uri.encode(js);
webView.loadUrl(url);

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.

Sign up to request clarification or add additional context in comments.

3 Comments

Not sure I am getting it. The callback is already a variable in sleepAlert?
Updated to give you an example
@GregRandall The callback function string passed to Java always be "undefined". Have you ever encountered this issue?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.