据我所知,有一种方法可以将 javascript 注入到 DOM 中。下面是使用 javascript 注入的示例代码webbrowser
控制:
HtmlElement head = webBrowser1.Document.GetElementsByTagName("head")[0];
HtmlElement scriptEl = webBrowser1.Document.CreateElement("script");
IHTMLScriptElement element = (IHTMLScriptElement)scriptEl.DomElement;
element.text = "function sayHello() { alert('hello') }";
head.AppendChild(scriptEl);
webBrowser1.Document.InvokeScript("sayHello");
有没有更简单的方法将 css 注入到 DOM 中?
我自己没有尝试过,但是由于 CSS 样式规则可以使用以下命令包含在文档中<style>
标签如下:
<html>
<head>
<style type="text/css">
h1 {color:red}
p {color:blue}
</style>
</head>
你可以尝试给予:
HtmlElement head = webBrowser1.Document.GetElementsByTagName("head")[0];
HtmlElement styleEl = webBrowser1.Document.CreateElement("style");
IHTMLStyleElement element = (IHTMLStyleElement)styleEl.DomElement;
IHTMLStyleSheetElement styleSheet = element.styleSheet;
styleSheet.cssText = @"h1 { color: red }";
head.AppendChild(styleEl);
走吧。您可以在 HTMLStyleElement 上找到更多信息here http://msdn.microsoft.com/en-us/library/aa768673(v=vs.85).aspx.
Edit
看来答案比我最初想象的要简单得多:
using mshtml;
IHTMLDocument2 doc = (webBrowser1.Document.DomDocument) as IHTMLDocument2;
// The first parameter is the url, the second is the index of the added style sheet.
IHTMLStyleSheet ss = doc.createStyleSheet("", 0);
// Now that you have the style sheet you have a few options:
// 1. You can just set the content as text.
ss.cssText = @"h1 { color: blue; }";
// 2. You can add/remove style rules.
int index = ss.addRule("h1", "color: red;");
ss.removeRule(index);
// You can even walk over the rules using "ss.rules" and modify them.
我编写了一个小测试项目来验证它是否有效。我通过在 MSDN 上搜索 IHTMLStyleSheet 得到了最终结果,偶然发现这一页 http://social.msdn.microsoft.com/Forums/en-US/ieextensiondevelopment/thread/49dc2c07-ea26-4734-aa2c-99a109ccb46a, 这一页 http://social.msdn.microsoft.com/Forums/en-US/winforms/thread/f18898b2-9313-4327-a4d9-6104831bfd69/ and this one http://social.msdn.microsoft.com/forums/en-US/iewebdevelopment/thread/33fd33f7-e857-4f6f-978e-fd486eba7174/.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)