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:

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: