2

Currently trying to inject CSS in a WebBrowser control using IHTMLStyleSheet

How to inject CSS in WebBrowser control?

I read this and I think it helped a bit but what's there doesn't seem to work for me.

        IHTMLDocument2 doc = (webBrowser1.Document.DomDocument) as IHTMLDocument2;
        IHTMLStyleSheet ss = doc.createStyleSheet("", 0);                        
        ss.addRule("body", "background-color:#000");
        ss.cssText = @"h1 { color: blue; }";

This is what I currently have, do I need to add it to the control after this or what am I doing wrong here?

EDIT: Got it working here's what I did

            CurrentDocument = (mshtml.HTMLDocument)webBrowser1.Document.DomDocument;
            styleSheet = CurrentDocument.createStyleSheet("", 0);

            StreamReader streamReader = new StreamReader(@"test.css"); //test.css is Stylesheet file
            string text = streamReader.ReadToEnd();
            streamReader.Close();
            styleSheet.cssText = text;
Robin
  • 51
  • 1
  • 6

2 Answers2

3

What I did to get it working

        CurrentDocument = (mshtml.HTMLDocument)webBrowser1.Document.DomDocument;
        styleSheet = CurrentDocument.createStyleSheet("", 0);

        StreamReader streamReader = new StreamReader(@"test.css"); //test.css is Stylesheet file
        string text = streamReader.ReadToEnd();
        streamReader.Close();
        styleSheet.cssText = text;
Robin
  • 51
  • 1
  • 6
0

I feel like you are trying to do this the hard-way.

Why not use the built-in winforms way of doing this instead of COM-Interop?

The easiest way would be to simply load your css file into memory and append it's string to the Style element of the web browser document. Or if you just want to change one particular element use the Style property

C#

using System.Windows.Forms;
namespace stackoverflow
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            webBrowser1.Navigate("http://www.google.com");
            webBrowser1.DocumentCompleted += WebBrowser1_DocumentCompleted;
        }
        private void WebBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
        {
            var FeelingLucky= webBrowser1.Document.GetElementById("gbqfbb");
            FeelingLucky.Style = "font-size: 40px;";

            var path = System.IO.Path.Combine(System.Environment.CurrentDirectory, "Stylesheet1.css");
            var StylesheetContent = System.IO.File.ReadAllText(path);
            var style= webBrowser1.Document.GetElementsByTagName("style")[0];
            style.InnerText = style.InnerText + " " + StylesheetContent;
        }
    }
}

CSS file

#lga {background-color: red;}

Here is google after the modifications above: Google

Take a look at the MSDN documentation on Style

Alexander Ryan Baggett
  • 2,347
  • 4
  • 34
  • 61