我一直在尝试使用 mshtml 修改第三方 web api。现在我正在尝试将两个元素的显示属性更改为无,以便它们不可见。
我知道他们的 ID。
第一个是img
,id是zendbox_close
。第二个是 div
,id 是 zenbox_scrim
。
html 看起来像这样
<div class="zenbox_header">
<img id="zenbox_close"></img>
</div>
...
<div id="zenbox_scrim...></div>
我想做的就是添加一些内联样式,所以它看起来像这样
<div class="zenbox_header">
<img id="zenbox_close" style="display:none;"></img>
</div>
...
<div id="zenbox_scrim style="display:none;"...></div>
在打开网页的 WPF WebBrowser
背后的代码中,我已经做到了这一点:
IHTMLDocument3 doc = (IHTMLDocument3)this._browser.Document;
IHTMLImgElement element = (IHTMLImgElement)doc.getElementById("zenbox_close");
我在另一篇文章中看到有人在谈论注入(inject)脚本,他们说你可以使用
IHTMLElement scriptEl = doc.CreateElement("script");
不过我不确定与此类似的 HTML 元素是什么。此外,我必须使用 IHTMLDocument3
来使用方法 getElementById
,但该类似乎不包含任何类似于 CreateElement()
的内容。
我的问题是如何将内联样式注入(inject)正在加载到我的 WPF
WebBrowser
中的 Document
?
最佳答案
是的,您可以内联操作样式。
执行此操作的一个好方法是在使用 IHTMLElement 时使用 IHTMLStyle 或 IHTMLCurrentStyle 接口(interface)。这两者反射(reflect)的值存在一些差异,并且它们并不总是同步的。更好的解释是:
IHTMLStyle vs IHTMLCurrentStyle
代码示例如下所示:
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
wb.LoadCompleted += wb_LoadCompleted;
wb.Source = new Uri("http://www.google.com");
}
void wb_LoadCompleted(object sender, NavigationEventArgs e)
{
var doc = wb.Document as HTMLDocument;
var collection = doc.getElementsByTagName("input");
foreach (IHTMLElement input in collection)
{
dynamic currentStyle = (input as IHTMLElement2).currentStyle.getAttribute("backgroundColor");
input.style.setAttribute("backgroundColor", "red");
}
}
}
关于c# - 如何将内联样式注入(inject)到我的 WPF WebBrowser 中加载的文档中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23740558/