How to inject CSS in WebBrowser control?

前端 未结 2 2037
心在旅途
心在旅途 2020-12-01 08:05

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:

<         


        
2条回答
  •  青春惊慌失措
    2020-12-01 08:46

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

    you could try giving:

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

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

    Edit

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

      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.
    

    I wrote a small test project to verify that this works. I arrived at this final result by doing a search on MSDN for IHTMLStyleSheet, upon which I happened across this page, this page and this one.

提交回复
热议问题