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

核能气质少年 提交于 2019-12-11 12:14:32

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/28818314/call-native-c-sharp-from-winjs-thats-loaded-in-a-webview

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!