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

问题描述 投票:1回答:2

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

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

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

我想这与以下事实有关:旧的IE版本不支持template标记,因此WebBrowser控件也不支持。我该如何解决?可能吗?

当然,我可以将模板放入字符串中并使用它来完成,但这似乎很hacky。

谢谢!

c# html .net winforms webbrowser-control
2个回答
1
投票

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。您可以在此处看到使用的简单步骤:Replace WebBrowser control by new WebView Compatible control for Windows Forms。它将在Windows 10上使用Edge渲染引擎,但对于其他Windows版本,它将再次使用IE。
  2. 您可以依赖其他您可以依赖其他浏览器控件,例如CefSharp

0
投票

它要么在您检索它时被索引/指向不存在的元素。

1)请检查您的指向是否正确,2)请检查ID是否确实已分类/设置3)请检查您是否确实定义了

© www.soinside.com 2019 - 2024. All rights reserved.