mercredi 21 février 2018

WebView using InvokeScriptAsync and calling a method and passing the parameters using JSON.parse [WebView,C#]

Calling a method on your WebView is simple just call the WebView.InvokeScriptAsync( method , param) (more information on MSDN) and you are good to go.  However imagine if you need to send json in the param, how do you send it?


This is the issue that we are going to have a quick look in the post, here is an example in of a javascript call that needs to be called with JSON data.  Looking at the MSDN documentation  , we can see that we need to surrond ou json string with JSON.parse({0}), in the params value in the InvokeScriptAsync.

Here is an example of the method name 'eval' and the javascript parameter that I would like to send to the UWP WebView:

 loadUrl javascript:object.load('xsazphf',
JSON.parse('{  
   "props":{  
      "param":{  
         "action":{  
            "gesture":"click",
            "id":"63825b13-dff5-4f45-81e9-a9dbe2aca39b"
         },
         "screen":{ 
            "id":"662dfa95-6ad2-43c1-b403-4e9a4118be4c"
         },
         "section":{  
            "id":"2bcd2be7-9c10-49e9-b71e-b77dee17c7fb",
            "index":1
         }
      }
   }
}'))

All in all,the json string that we want to pass to our javascript object needs to be wrapped in JSON.parse('{0}')).  This will allow the javascript to understand that the data that we are passing is JSON.

When we are building our string to call with the eval function in javasciprt  we will need to have some like this : myJsObject.MyMethode(Paramater1, ,JSON.parse("MyJSONStringFormat")) , when using StringBuilder we just need follow the pattern above.

Here is the code that will help you pass the correct string to your webview:

        public async void CallPlayerMethod(string method, string param, string json)
        {
            StringBuilder builder = new StringBuilder();
            builder.Append("myJSObject.");
            builder.Append(method);
            builder.Append(string.Format("('{0}'", param)) ;
            builder.Append(string.Format(",JSON.parse('{0}'))", json));  
// old
            //builder.Append('(');
            //builder.Append("'" + param + "'");
            //builder.Append(",JSON.parse('" + json + "')");
            //builder.Append(')');
//call webview CallEvalWebviewMethod(builder.ToString()); } private async void CallEvalWebviewMethod(string callMethod) {
            List<string> callingJsMethod = new List<string>();
            callingJsMethod.Add(callMethod);

            try
            {
                await MyWebView?.InvokeScriptAsync("eval", callingJsMethod);
            }
            catch (Exception e)
            {
                //silent fail
            }
        }

You can find my sample here
Happy coding