我在WinForm表单上具有WebBrowser
控件,该控件应显示特定的HTML页面。在HTML页面中,我有一些<template>
应该用于填充页面。当我使用以下代码时:
string template = webBrowser.Document.GetElementById("template-id").InnerHtml
我得到null
,而不是实际的内部HTML。
我想这与以下事实有关:旧的IE版本不支持template
标记,因此WebBrowser
控件也不支持。我该如何解决?可能吗?
当然,我可以将模板放入字符串中并使用它来完成,但这似乎很hacky。
谢谢!
WebBrowser控件使用Internet Explorer,并且Internet Explorer不支持<template>
标记。 (请参阅Browser compatibility)部分。
如果您可以修改页面的内容,则可以使用一些解决方法来使用<template>
标签。您可以使用以下任一选项:
选项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-在页面中包含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)请检查您的指向是否正确,2)请检查ID是否确实已分类/设置3)请检查您是否确实定义了