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>');");


    }
}

1 Answer 1

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(" + ...
Sign up to request clarification or add additional context in comments.

1 Comment

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

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.