Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WebBrowser.Document.Body is always null

I have a WebBrowser document set to be in edit mode. I am trying to manipulate the inner text of the body element by using WebBrowser.Document.Body.InnerText, however, WebBrowser.Document.Body remains null.

Here is the code where I create the document contents:

private WebBrowser HtmlEditor = new WebBrowser();
public HtmlEditControl()
{
    InitializeComponent();
    HtmlEditor.DocumentText = "<html><body></body></html>";
    myDoc = (IHTMLDocument2)HtmlEditor.Document.DomDocument;
    myDoc.designMode = "On";
    HtmlEditor.Refresh(WebBrowserRefreshOption.Completely);
    myContentsChanged = false;
}

I can edit code and everything fine, but I don't understand why HtmlEditor.Document.Body remains null. I know I could always just reset the document body whenever I need to load text into the form, but I would prefer to understand why this is behaving the way it is, if nothing else then for the knowledge.

Any help on this is greatly appreciated.

like image 591
Bender the Greatest Avatar asked Feb 03 '23 11:02

Bender the Greatest


1 Answers

You have to wait for the Web Browser's DocumentCompleted event to fire for the DomDocument.Body to not be null. I just tested this to verify. I suppose the question still remains: how are you able to edit through the underlying COM interface when the document has not completely loaded?

I checked to see if the IHTMLDocument2 pointers were the same in DocumentCompleted and the constructor. They are, which might indicate that the underlying COM object reuses a single HTML document object. It seems like any changes you make in the constructor at least have a pretty good chance of getting overwritten or throwing an exception.

For example, if I do this in the constructor, I get an error:

IHTMLDocument2 p1 = (IHTMLDocument2) HTMLEditor.Document.DomDocument;

p1.title = "Hello world!";

If I do the same in a DocumentCompleted handler, it works fine.

Hope this helps. Thanks.

like image 155
Nathan Andrew Mullenax Avatar answered Feb 06 '23 10:02

Nathan Andrew Mullenax