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',

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(string.Format("('{0}'", param)) ;
            builder.Append(string.Format(",JSON.parse('{0}'))", json));  
// old
            //builder.Append("'" + param + "'");
            //builder.Append(",JSON.parse('" + json + "')");
//call webview CallEvalWebviewMethod(builder.ToString()); } private async void CallEvalWebviewMethod(string callMethod) {
            List<string> callingJsMethod = new List<string>();

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

You can find my sample here
Happy coding