2

What I want to do is basically what was answered here:

how to get html content from a webview?

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<WebView>(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:

enter image description here

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" +
                "('<html>'+document.getElementsByTagName('html')[0].innerHTML+'</html>');");


    }
}
Community
  • 1
  • 1
Mr. Phil
  • 1,099
  • 2
  • 14
  • 31

1 Answers1

1

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(" + ...
Sven-Michael Stübe
  • 14,560
  • 4
  • 52
  • 103
  • 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 http://i.imgur.com/lXWroHB.png – Mr. Phil Oct 03 '16 at 08:40