C#:将 CSS 注入 MSHTML 实例的最佳方法?
我正在尝试将一些伴随其他 HTML 的 CSS 注入到 C# 管理的 WebBrowser 控件中。 我尝试通过底层 MSHTML(DomDocument 属性)控件来实现此目的,因为此代码充当完整 IE8 BHO 的原型。
问题是,虽然我可以注入 HTML(通过 mydomdocument.body.insertAdjacentHTML)和 Javascript(通过 mydomdocument.parentWindow.execScript),但它完全拒绝我的 CSS 代码。
如果我将包含要插入的 HTML 的字符串与注入后的目标页面源进行比较,则 MSHTML 的源实际上将包含 除了 元素之外的所有内容,并且它的根本来源。
CSS 通过了 CSS 2.1 的 W3C 验证。 它不会做任何太棘手的事情,除了一些背景图像属性将图像直接嵌入到 CSS 中(例如 background-image: url("data:image/png;base64
)。 ..),并且注释掉这些行并不会改变结果。
更奇怪的是(我不确定这是否相关),我上周没有遇到任何问题。 ,在实际注入之前切换了一些处理要注入的 HTML 的代码后,它不再起作用,我自然认为我的更改之一可能是问题所在,但在注释掉所有逻辑并提供它之后。 HTML 仍然显示为未格式化的直字符串,
目前我正在注入 标记,尽管我已尝试注入
。 >
提前感谢您的帮助
!
I'm trying to inject some CSS that accompanies some other HTML into a C# managed WebBrowser control. I am trying to do this via the underlying MSHTML (DomDocument property) control, as this code is serving as a prototype of sorts for a full IE8 BHO.
The problem is, while I can inject HTML (via mydomdocument.body.insertAdjacentHTML) and Javascript (via mydomdocument.parentWindow.execScript), it is flat-out rejecting my CSS code.
If I compare the string containing the HTML I want to insert with the destination page source after injection, the MSHTML's source will literally contain everything except for the <style>
element and its underlying source.
The CSS passes W3C validation for CSS 2.1. It doesn't do anything too tricky, with the exception that some background-image properties have the image directly embedded into the CSS (e.g. background-image: url("data:image/png;base64
...), and commenting out those lines doesn't change the result.
More strangely (and I am not sure if this is relevant), was that I was having no problems with this last week. I came back to it this week and, after switching around some of the code that handles the to-be-injected HTML before actual injection, it no longer worked. Naturally I thought that one of my changes might somehow be the problem, but after commenting all that logic out and feeding it a straight string the HTML is still appearing unformatted.
At the moment I'm injecting into the <body>
tag, though I've attempted to inject into <head>
and that's met with similar results.
Thanks in advance for your help!
tom
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
最终我自己解决了这个问题:
我没有意识到 createStyleSheet 创建了一个在文档的 DOM 中仍然“活动”的指针...因此您不需要将创建的样式表附加回其父级。 我最终通过研究 Javascript 的动态 CSS 代码来解决这个问题,因为它们的实现几乎是相同的。
Ended up solving this myself:
What I didn't realize is that createStyleSheet creates a pointer that is still 'live' in the document's DOM... therefore you don't need to append your created stylesheet back to its parent. I ended up figuring this out by studying dynamic CSS code for Javascript as the implementations are pretty much identical.