从加载在 WebView 中的 WinJS 调用本机 C# [英] Call Native C# from WinJS that's loaded in a WebView

查看:27
本文介绍了从加载在 WebView 中的 WinJS 调用本机 C#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道可以通过创建 Windows 运行时组件然后将其添加为对 WinJS 的引用从 WinJS 调用本机 C#应用程序 -- 但是当 WinJS 应用程序加载到 WebView 中时,是否可以从 WinJS 应用程序执行相同的操作?

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?

我已经尝试过了,但是 WebView 中的 WinJS 应用程序似乎在完全不同的上下文中运行,并且没有找到符号,所以它崩溃并提供启动 VS2013 的新实例以尝试调试.

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.

推荐答案

您是对的,本机 JavaScript 应用程序的应用程序宿主上下文和 web 视图的上下文是两个不同的东西.只有应用程序宿主允许 JavaScript 与 WinRT 对话,这也适用于 WinRT 组件,因为组件的结构方式与 WinRT API 本身相同.实际上,您的问题与询问是否可以将 WinRT 组件加载到 Web 浏览器中的问题相同(因为 webview 本质上是一个 Web 浏览器控件),那么答案是否定的.

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.

让 webview 中的代码脱离上下文并与可以访问 WinRT API 的任何代码(JS、C# 等)对话的唯一方法是在 webview 中使用 window.external.notify.该应用程序将该消息作为来自 webview 的事件(在带有 x-ms-webview 的 JS 中,它是 MSWebViewScriptNotify,在带有 XAML WebView 的 C#/VB 中,它是 ScriptNotify).然后,应用程序可以处理参数调用 API 作为响应.

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.

当然,因为 window.external.notify 不像函数调用那样可以返回值,所以应用程序必须通过其 InvokeScriptAsync 方法将结果发送到 webview,使其成为异步关系.

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.

我在我的免费电子书使用 HTML、CSS 和 JavaScript 编写 Windows 应用商店应用程序,第二版http://aka.ms/BrockschmidtBook2.

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.

这篇关于从加载在 WebView 中的 WinJS 调用本机 C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆