Search code examples
c#winformswebbrowser-controldomouterhtml

Is it possible to set the outerHTML for a HTMLDocument?


Below is the code i use to alter the HTML displayed in IE. However it always throws exception - Could not set the outerHTML property. Invalid target element for this operation. Ain't it possible to set the outerHTML?

protected void AlterContent(ref HTMLDocument docInput, HTMLDocument docAlteredOutPut)
{
    try
    {
        if (docInput.body.tagName.ToLower() == "body" && docAlteredOutPut.body.innerHTML != null)
        {
            docInput.documentElement.outerHTML = docAlteredOutPut.documentElement.outerHTML;
        }
    }
    catch
    {
    }
}

Thanks.


Solution

  • You cannot replace the html for the<body>element. There's no need to, this works fine:

    public partial class Form1 : Form {
        public Form1() {
            InitializeComponent();
            webBrowser1.Url = new Uri("http://stackoverflow.com");
            webBrowser1.DocumentCompleted += webBrowser1_DocumentCompleted;
        }
        void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e) {
            var body = webBrowser1.Document.Body;
            body.InnerHtml = "pwned";
        }
    }