Calling a C# function through Javascript onClick event in WebView in Xamarin.Forms

十年热恋 提交于 2019-12-01 09:08:54
André Tamietti Quintão

Unfortunately when we talk about WebView on mobile. Call a c# function through javascript it's a bad way to follow. Because of webview, it's very limited to do that and a lot of problems that you probably will have on each platform too

So here we go a solution that works fine for me and I used it a lot

1) You won't need to implement a CustomRenderer, just on your xamarin.forms and HTML

2) This solution works to Call camera, download files in a native way, and anything else you want, just intercept de navigating event

3) On your HTML implemet in your tag

 "<a href=></a>" 

something like this:

"<a href='..MyOnclickMethod?objId='"+obj.Jid+">"
+ obj.Title+ "</a>"

4) On your Xamarin WebView

...
webview.Navigating+=WebView_Navigating
...


private void WebView_Navigating(object sender, WebNavigatingEventArgs e)
{
      string url = evt.Url;

      if (url.ToLower().Contains("..MyOnclickMethod"))
      {
         //do your code here...
            evt.Cancel = true;
      }
}

make sure that you calling evt.Cancel = true; To prevent the webview continuing process requisition

If the id not coming yet: The string that you mounted maybe is not correct If you sure about this and it not working yet, try the pass in

"<a href>" 

a valid URL with your id like

"<a href='www.google.com/?objId='"+obj.Jid+">"

I hope I have helped you

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!