Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to update DOM content inside WebBrowser Control in C#?

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 ?

like image 502
Ashraf Bashir Avatar asked Mar 26 '12 14:03

Ashraf Bashir


2 Answers

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");
like image 182
Ashraf Bashir Avatar answered Nov 09 '22 22:11

Ashraf Bashir


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.

like image 31
viniciushana Avatar answered Nov 10 '22 00:11

viniciushana