如何触发 HTML 表单的 onsubmit 事件?

How to fire the HTML form's onsubmit event?

我正在尝试使用 MSHTML 从 Delphi 应用程序中触发 HTML 表单的 onsubmit 事件。我尝试使用 IHTMLFormElement::submitIHTMLDocument4::FireEvent 方法,但其中 none 触发了表单的 onsubmit 事件。

这是我的第一次尝试:

var
  Document: IHTMLDocument4;
  FormElement: IHTMLFormElement;
begin
  Document := (WebBrowser.Document as IHTMLDocument4);
  FormElement := (Document as IHTMLDocument2).Forms.item('form', 0) as IHTMLFormElement;
  FormElement.submit;
end;

这是我的第二次尝试:

var
  Document: IHTMLDocument4;
  FormElement: IHTMLFormElement;
begin
  Document := (WebBrowser.Document as IHTMLDocument4);
  FormElement := (Document as IHTMLDocument2).Forms.item('form', 0) as IHTMLFormElement;
  Document.FireEvent('onSubmit', 'null');
  Document.FireEvent('onSubmit', FormElement.onsubmit);
end;

我做错了什么?如何触发 HTML 表单的 onsubmit 事件?

您的第一次尝试失败,因为 IHTMLFormElement::submit 方法没有触发 onsubmit 事件,此方法的参考说明如下:

The IHTMLFormElement::submit method does not invoke the HTMLFormElementEvents::onsubmit event handler.

您的下一次尝试失败,因为您试图在文档元素上触发事件(想象一下,如果有多个子元素附加了此事件,则此元素必须做出的决定)。除了你传递了错误的参数。尝试这样的事情(只是不要忘记在您的生产代码中添加适当的错误处理):

procedure TForm1.ButtonClick(Sender: TObject);
var
  Empty: OleVariant;
  EventObj: OleVariant;
  Document: IHTMLDocument2;
  FormElement: IHTMLElement3;
begin
  // get the document interface reference
  Document := (WebBrowser.Document as IHTMLDocument2);
  // generate an event object to pass event context information
  EventObj := (Document as IHTMLDocument4).CreateEventObject(Empty);
  // get the form element and fire the event
  FormElement := Document.forms.item('form', NULL) as IHTMLElement3;
  FormElement.FireEvent('onsubmit', EventObj);
end;

这里有一个例子 HTML 可以玩:

<!DOCTYPE html>
<html>
   <body>
      <form name="form" onsubmit="submitForm()">
         <input type="submit">
      </form>
      <script>
         function submitForm() {
             alert("The form was submitted!");
         }
      </script>
   </body>
</html>

转换为 IHTMLElement 并调用 Click 方法。

var
  Document: IHTMLDocument4;
  FormElement: IHTMLFormElement;
begin
  Document := (WebBrowser.Document as IHTMLDocument4);
  FormElement := (Document as IHTMLDocument2).Forms.item('form', 0) as IHTMLElement;
  FormElement.Click;
end;