如何在WebBrowser控件中注入CSS?

DEN*_*DEN 18 .net c# webbrowser-control winforms

据我所知,有一种方法可以将javascript注入DOM.下面是使用webbrowser控件注入javascript的示例代码:

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");
Run Code Online (Sandbox Code Playgroud)

有没有更简单的方法将css注入DOM?

par*_*cle 29

我自己没有尝试过,但由于CSS样式规则可以使用<style>标签包含在文档中,如下所示:

<html>
<head>
<style type="text/css">
    h1 {color:red}
    p {color:blue}
</style>
</head>
Run Code Online (Sandbox Code Playgroud)

你可以尝试给予:

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);
Run Code Online (Sandbox Code Playgroud)

一个去.您可以在此处找到有关IHTMLStyleElement的更多信息.

编辑

似乎答案比我原先想的要简单得多:

  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.
Run Code Online (Sandbox Code Playgroud)

我写了一个小测试项目,以验证这是否有效.我做了IHTMLStyleSheet MSDN上搜索,在我对面发生的事情得出这个最终结果这个网页,这个网页这一个.

  • 两件事情.第一:请提及引用的程序集和使用语句.否则很难使用你的代码.第二:在第一行中,它必须是末尾的"IHTMLDocument2"而不是"HTMLDocument2".要添加的程序集是MSHTML(Microsoft HTML Object Library).然后添加`using mshtml;`. (4认同)