Re: Delphi AutoFill fields in a WebPage

Posted by webmaster Guido on April 09, 2004

In Reply to: AutoFill fields in a WebPage posted by Giovanni Caramia p12316 on April 09, 2004

: After WebBrowser.Navigate, is possible to automatically fill some fields on the web page ?

: What i want to do is to fill up UID and Password so that my customer (my wife in the case) is not obliged to digit in every time.
: If it's possible, i can create a little DB with URLAddress, UID, Pass and ... with only a DoubleClick on the record, reach the page and compile the required fields.

I puzzled together the following code, and to my surprise -- it works ;-)

// Example: fill out 3 fields on a webpage. 
// If a field is found, continue to the next field; 
// else show an error message.
procedure TForm1.Button1Click(Sender: TObject);
begin
  if not FillForm(WebBrowser1, 'firstname', 'Jimi') then
    ShowMessage('Error: field NAME not found on page')
  else begin
    if not FillForm(WebBrowser1, 'lastname', 'Hendrix') then
      ShowMessage('Error: field LASTNAME not found on page')
    else begin
      if not FillForm(WebBrowser1, 'category', 'Music') then
        ShowMessage('Error: field CATEGORY not found on page');
    end;
  end; 
end; 
// Fill out the first field with the name "FieldName" with a value. 
// We assume that all the fields of the form(s) have different names.
function TForm1.FillForm(WB: TWebBrowser; FieldName, Value: string): Boolean;  
var  
  FormNr, ItemNr: integer;  
  TheForm: Variant;  
begin  
  Result := False;  
  // Check if there is at least one form in the document  
  if WB.OleObject.Document.All.Tags('FORM').Length = 0 then begin  
    ShowMessage('Error: no FORM found on page');
    Exit;  
  end;  
  // Process all forms of the document  
  for FormNr := 0 to WB.OleObject.Document.Forms.Length - 1 do begin  
    TheForm := WB.OleObject.Document.Forms.Item(FormNr); 
    // Process all forms of the document, stop if found  
    for ItemNr := 0 to WB.OleObject.Document.Forms.Item.length - 1 do
      try  
        // If the fieldname is found, try to fill out and stop  
        if TheForm.Item(ItemNr).Name = FieldName then begin  
          TheForm.Item(ItemNr).Value := Value;  
          Result := True;
        end;  
      except  
        Break;  
      end;
      if Result then Break; 
    end;
    // Remove next line if there are several forms in the document with the
    // same fieldnames an which should be set to the same value
    if Result then Break;
  end;  
end;  

Related Articles and Replies: