I\'m trying to use monodroid with webkit to create an app. I am having a problem with letting the html page call a javascript method, which would be an interface to a method
Adding this answer to complement the two options under "But I don't like run()!" in the jonp's asnwer (because I don't like run!).
The [Export]
attribute, which is now available, requires a paid edition of Xamarin.
If you are using the free edition, the following workaround might work for you.
Inherit from Android.Webkit.WebChromeClient
, override the OnJsAlert
method, and have your web page "call methods" by using the alert()
function, passing serialized data in the message.
This should be no problem because we need WebChromeClient anyway, and you are supposed to have full control over the web page source code too.
E.g.:
private class AlertableWebChromeClient : Android.Webkit.WebChromeClient
{
private const string XAMARIN_DATA_ALERT_TAG = "XAMARIN_DATA\0";
public override bool OnJsAlert(Android.Webkit.WebView view, string url, string message, Android.Webkit.JsResult result)
{
if (message.StartsWith(XAMARIN_DATA_ALERT_TAG))
{
//Parse 'message' for data - it can be XML, JSON or whatever
result.Confirm();
return true;
}
else
{
return base.OnJsAlert(view, url, message, result);
}
}
}
In the web page:
if (window.xamarin_alert_callback != null) {
alert("XAMARIN_DATA\0" + JSON.stringify(data_object));
}
The xamarin_alert_callback
is used as a flag and can be set in various ways (e.g. WebView.LoadURL(javascript:...)
or WebView.AddJavascriptInterface(something, "xamarin_alert_callback")
) to let the page know it runs under the alert-enabled browser.