【问题标题】:How to inject CSS inside an iframe in a WebView? UWP如何在 WebView 的 iframe 中注入 CSS? UWP
【发布时间】:2019-08-18 07:28:47
【问题描述】:

我想知道是否可以在 UWP 中做类似于 Stylish 为浏览器所做的事情,因为我已经为我在 WebView 中使用的网页编写了 CSS,但是这个网页有一个 iframe,所以我需要将 CSS 应用于以"https://webchat.botframework.com/" 开头的所有 URL 以使其正常工作(在 Stylish 上)

<WebView x:Name="WebView1" Source="https://www.blabla.net/bla/webchat.html" Width="490" Height="490" HorizontalAlignment="Center"/>

网页代码

<body>
    <iframe lang="fr-FR" id="chat" style="width: 60vw; height: 95vh; margin-left: 20vw" src=''></iframe>

    <script>
        document.getElementById("chat").src =
            "https://webchat.botframework.com/embed/BitWcVaClient2?userid=" + create_UUID() +
            "&username=WW&v=4.2&l=fr-FR&s=ceraZE8go0A.lpa7tzuJ1H_rOJdJKWXibqg_aBrVQrHhhd432kU2e-M";

        function create_UUID() {
            var dt = new Date().getTime();
            var uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
                var r = (dt + Math.random() * 16) % 16 | 0;
                dt = Math.floor(dt / 16);
                return (c == 'x' ? r : (r & 0x3 | 0x8)).toString(16);
            });
            return uuid;
        }
    </script>
</body>

【问题讨论】:

    标签: javascript c# css webview uwp-xaml


    【解决方案1】:

    你可以写一个js脚本,用js做css注入。然后通过InvokeScriptAsync使用eval函数运行脚本。但是注入是在原来的网页上添加新的东西,所以每次网页加载的时候,重复注入的过程,意味着每次都会触发InvokeScriptAsync。您可以在WebView的DOMContentLoaded中编写如下代码。

    string styleContent = "here is style content";
    string injectContent = $"var st= document.createElement('style');document.body.appendChild(st);st.innerHTML = `{styleContent}`;";
    await TestWeb.InvokeScriptAsync("eval", new string[] { injectContent });
    

    更新:

    如果你想在iframe中注入CSS,可以使用下面的js代码注入。'chat'是iframe的名字,你需要给iframe加上名字。

    private async void WebView_DOMContentLoaded(WebView sender, WebViewDOMContentLoadedEventArgs args)
    {
        string cssContent = "body{background:black;}";
        string eval = "var frame = window.frames['chat'];" +
                      "var style = frame.document.createElement('style');" +
                      "frame.document.body.appendChild(style);" +
                      $"style.innerHTML = {cssContent}; ";
        await sender.InvokeScriptAsync("eval", new string[] { cssContent });
    }
    

    【讨论】:

    • 感谢您的回答,但您确定您的脚本吗?
    • 我正在展示通过WebView与网页交互的方式。这是一个想法。具体代码需要根据你的实际情况进行适配。使用的时候别忘了替换styleContent。你在使用过程中遇到问题了吗?
    • 是.. string styleContent = "body{ background-color: #111 !important; }"; System.Exception: 'HRESULT 异常:0x80020101'
    • 我在VS2017中使用你的styleContent时没有报异常。你能提供一个可以重现问题的简单示例吗?
    • 我在WebView 之前调用了我的method 是我的错,现在它正在工作我只需要找到一种方法来为botframework URLs 启用CSS
    猜你喜欢
    • 2018-08-21
    • 2019-02-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-15
    • 2017-08-13
    相关资源
    最近更新 更多