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:
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>');");
}
}
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(" + ...
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.