【发布时间】:2017-07-19 19:05:12
【问题描述】:
我正在为 Xamarin.UWP 开发一个应用程序,它试图将 Javascript 注入本地 html 文件 (uri: ms-appdata:///local/index.html),如下所示:
async void OnWebViewNavigationCompleted(WebView sender, WebViewNavigationCompletedEventArgs args)
{
if (args.IsSuccess)
{
// Inject JS script
if (Control != null && Element != null)
{
foreach (var f in Element.RegisteredFunctions.Where(ff => !ff.IsInjected))
{
await Control.InvokeScriptAsync("eval", new[] { string.Format(JavaScriptFunctionTemplate, f.Name) });
f.Injected();
}
}
}
}
然后当调用 Javascript 方法时,它将调用 OnWebViewScriptNotify 方法,以便我可以在我的应用程序中处理请求。
问题是这对某些kind of security reasons 不起作用:
这是我们做出的一项政策决定,我们收到了反馈,因此我们 重新评估它。如果您使用相同的限制,则不适用 NavigateToStreamUri 和解析器对象。内部是这样 无论如何,ms-appdata:/// 会发生什么。
然后我尝试了在这种情况下的建议,即使用此处提到的解析器:https://stackoverflow.com/a/18979635/2987066
但这会对性能产生巨大影响,因为它会不断将所有文件转换为要加载的流,以及某些页面加载不正确。
然后我研究了使用AddWebAllowedObject 方法,如下所示:
private void Control_NavigationStarting(WebView sender, WebViewNavigationStartingEventArgs args)
{
if (Control != null && Element != null)
{
foreach (var f in Element.RegisteredFunctions)
{
var communicator = new HtmlCommunicator(f);
Control.AddWebAllowedObject("HtmlCommunicator", communicator);
}
}
}
HtmlCommunicator 在哪里:
[AllowForWeb]
public sealed class HtmlCommunicator
{
public JSFunctionInjection Function { get; set; }
public HtmlCommunicator(JSFunctionInjection function)
{
Function = function;
}
public void Fred()
{
var d = 2;
//Do something with Function
}
}
在我的 html 中是这样的:
try { window.HtmlCommunicator.Fred(); } catch (err) { }
但这也不起作用。
那么有没有办法解决这个可笑的限制?
【问题讨论】:
-
来自http://blog.damiendelaire.com/2016/06/communicating-back-and-forth-with.html我读到
For some weird reason you need to add create this in new WRC library and mark this class this [AllowForWeb]我会调查更多 -
我注意到上面的链接和this link 他们都使用
ms-app-web,所以我不确定最后一种方法是否适用于ms-app-data。将课程放在另一个 WRC 库中不起作用
标签: javascript c# xamarin uwp xamarin.uwp