What I want to do is basically what was answered here:
However, I'm working with Xamarin in C#, and the code given in the top answer is in java. I tried to translate it to C# as follows:
public class LoginWebViewController : Activity
{
WebView localWebView;
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
SetContentView(Resource.Layout.WebView);
localWebView = FindViewById(Resource.Id.LocalWebView);
localWebView.SetWebViewClient(new JustWebViewClient());
localWebView.LoadUrl(LoginOperations.GetTPLoginUrl());
localWebView.Settings.JavaScriptEnabled = true;
localWebView.AddJavascriptInterface(new MyJavaScriptInterface(this), "HtmlViewer");
}
class MyJavaScriptInterface
{
private Context ctx;
MyJavaScriptInterface(Context ctx)
{
this.ctx = ctx;
}
public void showHTML(String html)
{
Console.WriteLine(html);
}
}
}
But I get the following error:
I tried changing the class to public but it still gives the same error. What is wrong?
Additional code:
public class MyWebViewClient : WebViewClient
{
public override void OnPageFinished(WebView view, String url)
{
base.OnPageFinished(view,url);
Console.WriteLine("DONE LOADING PAGE");
view.LoadUrl("javascript:HtmlViewer.showHTML" +
"(''+document.getElementsByTagName('html')[0].innerHTML+'');");
}
}
Solutions1
Your constructor is not public and you have to inherit from Java.Lang.Object. You have to add the Export attribute, too.
class MyJavaScriptInterface : Java.Lang.Object
{
private Context ctx;
public MyJavaScriptInterface(Context ctx)
{
this.ctx = ctx;
}
public MyJavaScriptInterface(IntPtr handle, JniHandleOwnership transfer)
: base (handle, transfer)
{
}
[Export("showHTML")]
public void showHTML(string html)
{
Console.WriteLine(html);
}
}
And in your javascript code is an error, too. You are missing a opening ( after showHTML.
view.LoadUrl("javascript:HtmlViewer.showHTML(" + ...
Talk1:
Thanks for helping. For those following this, you'll probably need to add a reference to Mono.Android.Export.Dll when you use ExportAttribute or ExportFieldAttribute here i.imgur.com/lXWroHB.png