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

拥有回忆 提交于 2019-11-30 16:30:23

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!