Search code examples
javascriptc#windows-phone-8webview

How to pass data or communicate between C# and Javascript in Windows Phone 8.1 App


In a Windows Phone 8.1 app I'm running javascript code in a webview which needs to call a C# method and the C# method returns some string data. I need this string data in the javascript code from where the C# method was called previously. How can I do this data passing operation in Windows Phone 8.1 app?

To be more specific, I've trying to use somewhat following snippet in javascript:

var jsVariable = ClassName.MethodName(params);

ClassName is a class in C# and MethodName(params) is a method of the class.

As far I know, I can call the C# method with window.external.notify() from the javascript side, but how can I receive the data sent by the C# method that is just called.


Solution

  • In C# you can't directly access the methods of an object this way. But you can still call and get data returned from the c# methods by calling InvokeScriptAsync() method of WebView class.

    From the javascript code call window.external.notify(params) with params as which method to be called, parse this params in the c# code and execute the method there, send the result back to the javascript by calling WebViewName.invokeScriptAsync().

    You may find more here.