c# webview加载本地html,从Android中的Webview获取html内容(将Xamarin与C#结合使用)

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:

3f5cb0f31c1fd7c3f0ab0045dd62c79d.png

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值