我正在开发一个应用程序,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
方法,以便我可以在我的应用程序中处理请求。
问题是由于某种安全原因这不起作用:
这是我们做出的一项政策决定,我们已经收到了反馈,因此我们重新评估了它。如果将 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) { }
但这也不起作用。
那么有没有办法解决这个可笑的限制呢?