Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

browser

c#

web

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.

like image 351
RaphaelH Avatar asked Sep 25 '12 17:09

RaphaelH


1 Answers

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.

like image 101
Darin Dimitrov Avatar answered Nov 07 '22 17:11

Darin Dimitrov