Template 标签的 InnerHtml 在 WebBrowser 控件中返回 null

InnerHtml of Template tag returnes null in WebBrowser control

我在 WinForm 窗体上有一个 WebBrowser 控件,它应该显示特定的 HTML 页面。在 HTML 页面中,我有一些应该用于填充页面的 <template>s。当我使用以下代码时:

string template = webBrowser.Document.GetElementById("template-id").InnerHtml

我得到 null,而不是实际的内部 HTML。

我想这与旧 IE 版本不支持 template 标签有关,因此在 WebBrowser 控件中。我该如何解决?有可能吗?

当然,我可以将我的模板放入一个字符串中并完成它,但这看起来很老套。

谢谢!

WebBrowser 控件使用 Internet Explorer,而 Internet Explorer 不支持 <template> 标记。 (参见 Browser compatibility)部分。

是否可以修改页面内容

如果您可以修改页面内容,则可以使用一些解决方法来使用 <template> 标记。您可以使用以下任一选项:

  1. 选项 1 - 隐藏标签并以边缘模式加载 IE

    webBrowser1.DocumentText = @"
    <html>
    <head>
        <title>Test</title>
        <meta http-equiv=""X-UA-Compatible"" content=""IE=Edge"" />
    </head>
    <body>
        <h1>Test</h1>
        <div>This is a test page.</div>
        <template id=""template1"" style=""display:none;"">
            <h2>Flower</h2>
            <img src=""img_white_flower.jpg"" />
        </template>
    </body>
    </html>";
    webBrowser1.DocumentCompleted += (obj, args) =>
    {
        var element = webBrowser1.Document.GetElementById("template1");
        MessageBox.Show(element?.InnerHtml);
    };
    
  2. 选项 2 - 在页面中包含 The HTML5 Shiv

    webBrowser1.DocumentText = @"
    <html>
    <head>
        <title>Test</title>
        <!--[if lt IE 9]>
        <script src=""https://cdnjs.cloudflare.com/ajax/libs/html5shiv/3.7.3/html5shiv.min.js"">
        </script>
        <![endif]-->
    </head>
    <body>
        <h1>Test</h1>
        <div>This is a test page.</div>
        <template id=""template1"">
            <h2>Flower</h2>
            <img src=""img_white_flower.jpg"" />
        </template>
    </body>
    </html>";
    webBrowser1.DocumentCompleted += (obj, args) =>
    {
        var element = webBrowser1.Document.GetElementById("template1");
        MessageBox.Show(element?.InnerHtml);
    };
    

如果无法修改页面内容

如果无法修改页面内容,则需要使用不同的浏览器控件,例如:

  1. 您可以使用新的WebViewCompatible control for Windows Forms. You can see simple steps to use here: Replace WebBrowser control by new WebView Compatible control for Windows Forms。 Windows 10 将使用 Edge 渲染引擎,但对于其他 windows 版本,它再次使用 IE。
  2. 您可以依赖其他您可以依赖其他浏览器控件,例如 CefSharp