0

我正在开发一个应用程序,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) { }

但这也不起作用。

那么有没有办法解决这个可笑的限制呢?

4

1 回答 1

0

所以我找到了这个答案:C# class attributes not access in Javascript

它说:

我相信您需要定义以小写字符开头的方法名称。

例如:将 GetIPAddress 更改为 getIPAddress。

我在我这边测试了它,发现如果我使用大写名称“GetIPAddress”,它就不起作用。但如果我使用 getIPAddress,它就可以工作。

所以我尝试了这个:

我按照这里Windows Runtime Component的建议创建了一个类型的新项目,并将方法名称更改为小写,所以我有:

[AllowForWeb]
public sealed class HtmlCommunicator
{
    public HtmlCommunicator()
    {
    }

    public void fred()
    {
        var d = 2;
        //Do something with Function
    }
}

在我的javascript中,我有:

try { window.HtmlCommunicator.fred(); } catch (err) { }

在我的主要 UWP 项目中,我引用了新Windows Runtime Component库并具有以下内容:

public HtmlCommunicator communicator { get; set; }

private void Control_NavigationStarting(WebView sender, WebViewNavigationStartingEventArgs args)
{
    if (Control != null && Element != null)
    {
        communicator = new HtmlCommunicator();
        Control.AddWebAllowedObject("HtmlCommunicator", communicator);
    }
}

这行得通!

于 2017-03-01T09:45:51.480 回答