[英]Get html content from webview in Android (using Xamarin with C#)
What I want to do is basically what was answered here:我想要做的基本上就是这里的回答:
how to get html content from a webview? 如何从 webview 获取 html 内容?
However, I'm working with Xamarin in C#, and the code given in the top answer is in java.但是,我正在使用 C# 中的 Xamarin,并且顶部答案中给出的代码是在 java 中。 I tried to translate it to C# as follows:
我尝试将其转换为 C#,如下所示:
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.我尝试将类更改为 public,但它仍然给出相同的错误。 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
.您的构造函数不是公共的,您必须从
Java.Lang.Object
继承。 You have to add the Export
attribute, too.您还必须添加
Export
属性。
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.并且在您的 javascript 代码中也是一个错误。 You are missing a opening
(
after showHTML
.您缺少一个开头
(
在showHTML
之后。
view.LoadUrl("javascript:HtmlViewer.showHTML(" + ...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.