Cry about...
Delphi Programming with TWebBrowser

Example of how to call the W3C HTML validator from TWebBrowser

The following code sample was kindly provided to me by Anthony Naylon. It illustrates how to pass a block of HTML to the W3C HTML validator. It uses many of the ideas found in "How to read and write form elements".

Using a TWebBrowser component this example performs all of the steps necessary to upload an HTML document to the W3C HTML validator and display the returned HTML results page. This procedure automates the process of manually pasting the HTML code (stored in the variable "html_code") into the form field "Validate by Direct Input" and pressing the button "Check".

An alternative would be to paste the name of the local HTML file to be validated into the field "Validate by File Upload". This is not possible to automate, however, because this field is of the type "file", which for security reasons blocks any attempt to programmatically upload a file.

After this procedure is executed, the form containing the TWebBrowser is shown.

procedure validate_html(const html_code : string);
  var d : ihtmldocument2;   // Document
      f : ihtmlformelement; // Form
  screen.cursor := crhourglass;
  // Wait until the validation input form is loaded
  while webbrowser.ReadyState < READYSTATE_INTERACTIVE do
  // Get the document that is contained in "webbrowser"
  d := webbrowser.document as ihtmldocument2;
  // Get the document form (third form, so number = 2)
  // that contains the field that we want to fill
  f := (d.forms as ihtmlelementcollection).item(2,'') as ihtmlformelement;
  // Fill the textarea field "Validate by Direct Input", which is
  // called "fragment" in the Web page HTML, with the HTML code
  (f.item('fragment','') as ihtmltextareaelement).value := html_code;
  // Submit the form
  // Wait until the validation results are loaded
  while webbrowser.ReadyState < READYSTATE_INTERACTIVE do
  screen.cursor := crdefault;

If you use this code sample I suggest adding a call to Sleep(5) in both of the while loops - this stops the code from being processor bound and the user is unlikely to notice a delay of a few milliseconds.

These notes are believed to be correct for Delphi 7 and may apply to other versions as well.

About the author: is a dedicated software developer and webmaster. For his day job he develops websites and desktop applications as well as providing IT services. He moonlights as a technical author and consultant.