c# - 如何在 WebBrowser 控件中注入(inject) CSS?

标签 c# .net winforms webbrowser-control

据我所知,有一种方法可以将 javascript 注入(inject) DOM。下面是使用 webbrowser 控件注入(inject) 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");

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

最佳答案

我自己没有尝试过,但是因为可以使用 <style> 将 CSS 样式规则包含在文档中标记如下:

<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);

去吧。您可以在 IHTMLStyleElement here 上找到更多信息.

编辑

看来答案比我原先想的要简单得多:

  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 得出了这个最终结果,我偶然发现了 this page。 , this pagethis one .

关于c# - 如何在 WebBrowser 控件中注入(inject) CSS?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5496549/

相关文章:

c# - 无法使用 C# .NET Core 对 ING (api.sandbox.ing.com) 端点进行证书授权 API 调用

c# - 如何使用 C# 在 Powerpoint 2013 中获取鼠标光标下的单词?

c# - 使用 CultureInfo 时 DateTime.Parse 返回错误值

.net - ReactiveUI 如何正确使用 WhenAnyObservable

c# - 如何以编程方式选择 ListView 中的项目?

c# - 快速流畅地滚动图像

c# - Lock 关键字不能按预期使用字符串

c# - 参数名称 : root cannot be Null exception Ninject

.net - 使用 MSBuild 签署 ClickOnce 或程序集会导致错误 MSB3321

c# - 实时调整表格大小的矩形?