Search code examples
windows-8windows-runtimeuwpwinjs

Call Native C# from WinJS that's loaded in a WebView


I know it's possible to call native C# from WinJS by creating a Windows Runtime Component and then adding it as a reference to the WinJS app -- but is it possible to do the same thing from the WinJS app when it's loaded inside a WebView?

I've tried it, but it seems the WinJS app inside the WebView is operating in a completely different context or something and isn't finding the symbols, so it crashes and offers to launch a new instance of VS2013 to try and debug.


Solution

  • You're correct in that the app host context for a native JavaScript app and the context for a webview are two different things. Only the app host allows JavaScript to talk to WinRT which applies also to WinRT components, as components are structured in the same way that the WinRT APIs are themselves. In effect, your question is the same as asking whether you can load a WinRT component into a web browser (because the webview is a web browser control, essentially), then the answer is no.

    The only way for code inside a webview to get out of that context and talk to any code (JS, C#, etc.) that can access WinRT APIs, is to use window.external.notify from within the webview. The app picks up that message as an event coming from the webview (in JS with x-ms-webview it's MSWebViewScriptNotify, in C#/VB with the XAML WebView it's ScriptNotify). The app can then process arguments call APIs in response.

    Of course, because window.external.notify does not act like a function call in that you can return a value, the app would have to send results to the webview through its InvokeScriptAsync method, making it an asynchronous relationship.

    I talk more about the details in Chapter 4 (starting on page 204) of my free ebook, Programming Windows Store Apps with HTML, CSS, and JavaScript, 2nd Edition, http://aka.ms/BrockschmidtBook2.