Passing json string to webview js function in Xamarin Forms

Newbie Dev 156 Reputation points
2021-11-26T14:19:11.227+00:00

In my Xamarin forms project, I am trying to pass a viewmodel object to a webview. The WebView uses the information from the viewmodel to display some information on the local html file.

I was able to add the .html file (with Azure Maps) to the respective folders in different platforms and call them from the View.xaml.cs in shared Xamarin forms project.

But I am unable to send a viewmodel object to the WebView. Any suggestions?

The below is the code used to pass values to js function in the html file

string jsonString = JsonSerializer.Serialize(vm);
  await WebView.EvaluateJavaScriptAsync($"jsFunction({jsonString})");

And code in the jsfuction in the html page is as below,

 var Details = [];

 function jsFunction(models) {
      Details = JSON.parse(models);
 }

But the values are not getting passed to the html page or the js method is not being called.

I tried to debug the WebView from chrome, but it chrome devices webview inspect is loading only after the webview is loaded, so I am unable to see what the "Details" parameter has in it.

Also tried the Eval(), but the same happend.

 WebView.Eval(string.Format("jsFunction({0})", jsonString));

I only want to pass data to the webview, so not sure if custom webview would be an option(because the documentation mentioned calling c# from webview).

Thanks in advance.

Developer technologies .NET Xamarin
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. Anonymous
    2021-11-27T04:11:13.58+00:00

    Hello,​

    Welcome to our Microsoft Q&A platform!

    I transfer Json data in the custom renderer. Before I pass the string to the evaluateJavascript method, I replace the \ to \\\ with string unescaped = jsonString.Replace("\"", "\\\"");.

    And I transfer json data to the webview in OnPageFinished for testing.

       internal class MyWebViewClient : WebViewClient  
           {  
               public override void OnPageFinished(Android.Webkit.WebView view, string url)  
               {  
                   base.OnPageFinished(view, url);  
         
                   MyViewModel viewModel = new MyViewModel();  
                   string jsonString = System.Text.Json.JsonSerializer.Serialize(viewModel);  
                   string unescaped = jsonString.Replace("\"", "\\\"");  
                   view.EvaluateJavascript("javascript: " + "updateFromAndroid1(\"" + unescaped + "\")", null);  
               }  
           }  
    

    My html page just have a JavaScript method called updateFromAndroid1(message) to push a alert window for testing.

    Here is my custom renderer code. I create MyViewModel for testing. And I install System.Text.Json nuget package for Json Serializer。

       [assembly: ExportRenderer(typeof(HybridWebView), typeof(HybridWebViewRenderer))]  
       namespace WebviewInvokeJS.Droid  
       {  
         
           public class MyViewModel  
           {  
               public string MyProperty { get; set; }  
               public MyViewModel()  
               {  
                   MyProperty = "Name";  
         
               }  
         
           }  
           public class HybridWebViewRenderer : WebViewRenderer  
           {  
               Context _context;  
               public HybridWebViewRenderer(Context context) : base(context)  
               {  
                   _context = context;  
               }  
               protected override void OnElementPropertyChanged(object sender, PropertyChangedEventArgs e)  
               {  
                   if (Control != null)  
                   {  
                       Control.Settings.JavaScriptEnabled = true;  
                       Control.LoadUrl("file:///android_asset/table.html");  
                       Control.SetWebViewClient(new MyWebViewClient());  
                   }  
         
                   base.OnElementPropertyChanged(sender, e);  
               }        
           }  
         
           internal class MyWebViewClient : WebViewClient  
           {  
               public override void OnPageFinished(Android.Webkit.WebView view, string url)  
               {  
                   base.OnPageFinished(view, url);  
         
                   MyViewModel viewModel = new MyViewModel();  
                   string jsonString = System.Text.Json.JsonSerializer.Serialize(viewModel);  
                   string unescaped = jsonString.Replace("\"", "\\\"");  
                   view.EvaluateJavascript("javascript: " + "updateFromAndroid1(\"" + unescaped + "\")", null);  
         
               }  
           }  
       }  
    

    Best Regards,

    Leon Lu


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.


Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.