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

标签 delphi mshtml twebbrowser

我正在尝试使用 MSHTML 从 Delphi 应用程序触发 HTML 表单的 onsubmit 事件。我尝试使用 IHTMLFormElement::submitIHTMLDocument4::FireEvent 方法,但它们都没有触发表单的 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>

关于delphi - 如何触发 HTML 表单的 onsubmit 事件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32104009/

相关文章:

delphi - 如何更改禁用的 TComboBox 的字体颜色?

multithreading - Delphi (Indy) 线程安全类

delphi - Inno Setup Delphi DLL中的Unicode版本和字符串参数

c# - 在循环中使用 Microsoft.MSHTML,内存泄漏

delphi - 通过 Delphi 在网页上按下按钮

德尔福 "IdHTTP.Request.Range"属性 : undeclared identifier

c# - 切换到其他框架(.Net WebBrowser、MsHTML)时拒绝访问跨域异常

vb.net - 如何在 VB.NET 中使用 MSHTML?

delphi - 在网络浏览器中打开页面

delphi - Delphi TWebBrowser.GoBack:如何处理重定向