How can Delphi call JS methods through WebBrowser?

In Delphi, you can call JavaScript methods by using the Document property of WebBrowser. Here are the specific steps:

  1. Place a TWebBrowser control on a form in Delphi and make sure the SHDocVw unit has been imported.
  2. In events that require calling JavaScript methods, use the WebBrowser’s Document property to access the current webpage’s HTML document object. You can obtain the Document object using the following code:
var
  Doc: OleVariant;
begin
  Doc := WebBrowser1.Document;
  1. Once you have obtained the Document object, you can use the parentWindow property of the Document to access the global window object in JavaScript. You can obtain the window object using the following code:
var
  Window: OleVariant;
begin
  Window := Doc.parentWindow;
  1. By accessing the window object, you can now call JavaScript methods. Use the execScript method of the window object to execute JavaScript code. You can use the following code to call JavaScript methods:
Window.execScript('JavaScript代码');

For example, to call a JavaScript method named “myFunction,” you can use the following code:

Window.execScript('myFunction();');

In summary, the complete code for invoking a JavaScript method is as follows:

var
  Doc, Window: OleVariant;
begin
  Doc := WebBrowser1.Document;
  Window := Doc.parentWindow;
  Window.execScript('myFunction();');
end;

The above are the basic steps for calling JavaScript methods in Delphi using the WebBrowser control. Please make necessary modifications and extensions based on your actual situation.

bannerAds