【问题标题】:Injecting local JS/CSS File to UWP WebView将本地 JS/CSS 文件注入 UWP WebView
【发布时间】:2018-08-21 10:27:42
【问题描述】:

因为在知道人们一直在做什么之前只是调用实际网页中已经存在的脚本。

    private void LoadHtml()
    {
        WebViewControl.Source = new Uri("https://www.twitter.com");
    }

首先我加载一个我想修改其样式的页面。我可以通过注入应用程序本地文件夹中可用的 CSS 文件来做到这一点。

  private async void InvokeScript()
    {
        // Invoke the javascript function called 'addCSS' that is loaded into the WebView.
        try
        {
            string result = await WebViewControl.InvokeScriptAsync("addCSS", null);
            rootPage.NotifyUser($"Script returned \"{result}\"", NotifyType.StatusMessage);
        }
        catch (Exception ex)
        {
            string errorText = null;
            switch (ex.HResult)
            {
                case unchecked((int)0x80020006):
                    errorText = "There is no function called doSomething";
                    break;
                case unchecked((int)0x80020101):
                    errorText = "A JavaScript error or exception occured while executing the function doSomething";
                    break;

                case unchecked((int)0x800a138a):
                    errorText = "doSomething is not a function";
                    break;
                default:
                    // Some other error occurred.
                    errorText = ex.Message;
                    break;
            }
            rootPage.NotifyUser(errorText, NotifyType.ErrorMessage);
        }

然后我会调用 addCSS 函数。当然这不会起作用,因为 Twitter.com JS Code 没有这个功能。

我想知道的是如何调用一个 JS 函数,它将一个新的 CSS 文件放入 webview 中的当前网页中。

【问题讨论】:

    标签: c# webview uwp


    【解决方案1】:

    我想知道的是如何调用一个 JS 函数,它将一个新的 CSS 文件放入 webview 中的当前网页中。

    您可以在您的项目文件夹中创建一个CSS 文件,然后使用InvokeScriptAsync 方法调用JavaScript eval 函数,如下所示。

    MyCss.css

    body {
        background-color:rebeccapurple;
    }
    

    用法

    string functionString = "var link = document.createElement('link'); link.rel = 'stylesheet'; link.type = 'text/css';  link.href = 'ms-appx-web:///MyCss.css'; document.getElementsByTagName('head')[0].appendChild(link); ";
    await MyWebView.InvokeScriptAsync("eval", new string[] { functionString });
    

    请注意WebView 仅支持使用ms-appx-web 方案的应用程序包中的内容,以及使用httphttps URI 方案的Web 内容。它不适用于位于应用程序本地文件夹中的资产。所以在这里使用file:///ms-appdata:///ms-appx:/// 方案将不起作用。

    【讨论】:

      猜你喜欢
      • 2019-02-02
      • 1970-01-01
      • 2017-08-13
      • 1970-01-01
      • 1970-01-01
      • 2019-05-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多