Thursday, 24 July 2008

.Net WebBrowser Control & DocumentComplete event

Lately I've been developing a new application that includes an embedded web browser. The application loads specific web pages and then reads and writes to the fields on the page. For example, it might set some fields to text values defined by the user or read the value of a combo/ dropdown to see if a user-defined criteria is met.

The fundamentals of the new application were working OK but under some conditions my code failed to access the fields on a loaded web page. The access code is executed in the .Net WebBrowser control's DocumentCompleted event.

The DocumentCompleted event is fired after calling the control's Navigate method to load a web page. After some investigation I found that the DocumentCompleted event was being called more than once when a page was loaded. What I had to do in the event was test the WebBrowser's ReadyState property and check that the state was Complete. Only when a Complete state was set could the DocumentCompleted event run code to access the HTML fields on the web page. The DocumentCompleted event might be fired many times as a page is loaded but any code accessing the WebBrowser's Document property should only be executed if the ReadyState property has a value of Complete.

No comments: