C #: Best way to embed CSS in an MSHTML instance?

I am trying to add some CSS that accompanies some other HTML code to a C # WebBrowser control. I am trying to do this using the MSHTML (DomDocument) main control, as this code serves as a sort prototype for the full IE8 BHO.

The problem is that I can embed HTML (through mydomdocument.body.insertAdjacentHTML) and Javascript (through mydomdocument.parentWindow.execScript), it completely excludes my CSS code.

If I compare the string containing HTML that I want to insert with the source of the landing page after the injection, the MSHTML source will literally contain everything except the <style> element and its main source.

CSS passes the W3C test for CSS 2.1. This does not do anything complicated, except that some properties of the background image have an image directly embedded in CSS (for example, background-image: url("data:image/png;base64 ...), and commenting on these lines does not change result.

More weird (and I'm not sure if this is relevant) was that I had no problems from last week. I returned to it this week, and after switching the code that processes the HTML code before injection, it no longer works. Naturally, I thought that one of my changes might somehow be a problem, but after commenting all this logic and submitting its straight line, the HTML still looks unformatted.

At the moment, I am inserting into the <body> , although I tried typing in <head> and met similar results.

Thanks in advance for your help!

Tom

+3
source share
1 answer

It ended on its own:

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

I did not understand that createStyleSheet creates a pointer that still "lives" in the DOM document ... so you do not need to add the created stylesheet back to its parent element. I ended up understanding this by learning the dynamic CSS for Javascript, as the implementations are almost identical.

+15
source

Source: https://habr.com/ru/post/1210635/


All Articles