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

前端 未结 1 1353
没有蜡笔的小新
没有蜡笔的小新 2021-01-06 08:29

I have a post type WebView which I managed to bind with the service response as string but I have some links like related posts which have their ids. On clickin

相关标签:
1条回答
  • 2021-01-06 08:45

    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 the navigating event

    3) On your HTML implement 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 evt)
    {
          string url = evt.Url;
    
          if (url.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

    0 讨论(0)
提交回复
热议问题