Reputation: 2184
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.
Upvotes: 29
Views: 15169
Reputation: 32085
You could do this in a setInterval
callback with a reasonable interval (~20ms) and then clear the interval at an appropriate time such as on DOM ready.
The only caveat is that your callback would need to be idempotent since it will get called multiple times. I don't suspect that should be difficult if you simply add a data attribute or classname to the DOM nodes you have already modified so they don't get modified again.
Upvotes: 0
Reputation: 36058
This does not work. I am facing the same problem. What if you want to modify ajax calls? The navigate method never fires. Also the navigate method never fires on iFrames.
I think the only solution is to use a proxy. Just click on add NuGet packages. Search for fiddlercore. Once you add a reference to http://www.telerik.com/fiddler/fiddlercore . Now just do a google search on how to modify a response using FiddlerCore. I am sure there will be lots of examples.
Note: when starting fiddler core by default it will change your computers proxy settings. You do not want that! you only want your webbrowser control to connect to it not your whole system. So initialize fidderl core to listen at a random port without starting as a system proxy. Then set your webbrowser control to connect to that proxy.
It will get trickier when trying to access HTTPS sites :/
Upvotes: 0
Reputation: 1038850
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
.
Upvotes: 17