C#: Best way to inject CSS into MSHTML instance?

后端 未结 1 1355
深忆病人
深忆病人 2021-01-03 10:06

I\'m trying to inject some CSS that accompanies some other HTML into a C# managed WebBrowser control. I am trying to do this via the underlying MSHTML (DomDocument property)

1条回答
  •  时光说笑
    2021-01-03 10:56

    Ended up solving this myself:

    mshtml.HTMLDocument test = (mshtml.HTMLDocument)webBrowser1.Document.DomDocument;
    
    //inject CSS
    if (test.styleSheets.length < 31) { // createStyleSheet throws "Invalid Argument if >31 stylesheets on page
    
        mshtml.IHTMLStyleSheet css = (mshtml.IHTMLStyleSheet)test.createStyleSheet("", 0);
        css.cssText = myDataClass.returnInjectionCSS(); // String containing CSS to inject into the page
            // CSS should now affect page
    
    } else {
        System.Console.WriteLine("Could not inject CSS due to styleSheets.length > 31");
        return;
    }

    What I didn't realize is that createStyleSheet creates a pointer that is still 'live' in the document's DOM... therefore you don't need to append your created stylesheet back to its parent. I ended up figuring this out by studying dynamic CSS code for Javascript as the implementations are pretty much identical.

    0 讨论(0)
提交回复
热议问题