代码之家  ›  专栏  ›  技术社区  ›  user9035043

将本地JS/CSS文件注入UWP WebView

  •  0
  • user9035043  · 技术社区  · 7 年前

    因为直到知道人们在做什么,才调用实际网页中已经存在的脚本。

        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函数。当然,自从推特之后,这就行不通了。com JS代码没有此函数。

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

    1 回复  |  直到 7 年前
        1
  •  1
  •   Nico Zhu    7 年前

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

    你可以 CSS 文件,然后使用 InvokeScriptAsync 方法调用JavaScript 评估 功能就像follow一样。

    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 以及使用 http https URI方案。它无法处理位于应用程序本地文件夹中的资产。所以使用 file:/// ,则, ms-appdata:/// ms-appx:/// 这个计划在这里行不通。