Changing the HTML in a WebBrowser before it is displayed to the user?

browser, c#, web

Solution

You could do the DOM manipulation inside the `Navigated` event:

webBrowser1.Navigated += (sender, e) =>
{
    ((WebBrowser)sender).Document.GetElementById("Text").InnerHtml = "Bye";
};

This will execute before any DOM ready handlers in the document. So for example if you had the following HTML initially:

<html>
<head>
    <title>Test</title>
</head>
<body onload="document.getElementById('Text').innerHTML = document.getElementById('Text').innerHTML + ' modified';">
    <p id="Text">Hello</p>
</body>
</html>

When you display this code in the WebBrowser you will get `Bye modified`.

Problem

I'm using a WebBrowser Control and I'd like to manipulate the HTML Code before it gets displayed in the Control. For example open Website A with following content: ``` <html> <body> <p id="Text">Hello</p> </body> </html> ``` I would like to change it to ``` <html> <body> <p id="Text">Bye</p> </body> </html> ``` I know I could do that with DocumentCompleted event and then manipulate it. But if the Website executes JavaScript stuff which gets executed on Document ready event, it wouldn't make sense to change it, because it has already been executed.

Original source