6

I've a windows .Net Form which contains a WebBrowser Control.
This WebBrowser displays a webpage based on its Url property.
Can I modify the DOM of the displayed page inside the WebBrowser control ?
If yes, how to ?

Ashraf Bashir
  • 9,686
  • 15
  • 57
  • 82
  • 2
    It is possible. WebBrowser is supposed to have a property called Document which you can access the html through htmldocument on managed code (http://msdn.microsoft.com/en-us/library/system.windows.forms.webbrowser.aspx) – MilkyWayJoe Mar 26 '12 at 14:18
  • 2
    Here's the link to that specific property I mentioned http://msdn.microsoft.com/en-us/library/system.windows.forms.webbrowser.document.aspx – MilkyWayJoe Mar 26 '12 at 14:21
  • 1
    Is it read only (as I see it only contains a getter) ? – Ashraf Bashir Mar 26 '12 at 15:23

2 Answers2

10

For those who are interested, here's the solution:

HtmlElement headElement = webBrowser1.Document.GetElementsByTagName("head")[0];
HtmlElement scriptElement = webBrowser1.Document.CreateElement("script");
IHTMLScriptElement domScriptElement = (IHTMLScriptElement)scriptElement.DomElement;
domScriptElement.text = "function applyChanges(){/*DO WHATEVER YOU WANT HERE*/}";
headElement.AppendChild(scriptElement);

// Call the nextline whenever you want to execute your code
webBrowser1.Document.InvokeScript("applyChanges");
Ashraf Bashir
  • 9,686
  • 15
  • 57
  • 82
3

From http://msdn.microsoft.com/pt-br/library/system.windows.forms.webbrowser.aspx:

You can also manipulate the contents of a Web page through the Document property, which contains an HtmlDocument object that provides managed access to the HTML document object model (DOM) for the current page. This property is useful, when used in combination with the ObjectForScripting property, to implement two-way communication between your application code and dynamic HTML (DHTML) code in a Web page, letting you combine Web-based controls and Windows Forms controls in a single user interface. You can use the Document property to call scripting code methods from your application. Your scripting code can access your application through the window.external object, which is a built-in DOM object provided for host access, and which maps to the object that you specify for the ObjectForScripting property.

viniciushana
  • 235
  • 1
  • 2
  • 12