如何注入CSS在WebBrowser控件?控件、CSS、WebBrowser

2023-09-02 01:42:06 作者:深情不如久伴。

按我所知,没有办法的javascript到DOM注入。下面是示例code表示注入的JavaScript与 web浏览器控制:

As per my knowledge,there is a way to inject javascript into the DOM. Below is the sample code that injects javascript with the webbrowser control:

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?

Is there an easier way to inject css into the DOM?

推荐答案

我没有尝试这个自己,但由于CSS样式规则可以使用包含在文档中的<风格> 标签中:

I didn't try this myself but since CSS style rules can be included in a document using the <style> tag as in:

<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 更多信息。

a go. You can find more info on the IHTMLStyleElement here.

看来答案是非常非常简单的,比我原来想象:

It seems the answer is much much simpler than I originally thought:

  IHTMLDocument2 doc = (webBrowser1.Document.DomDocument) as HTMLDocument2;
  // 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页面,this页面和this 之一。

 
精彩推荐
图片推荐