procedure TForm1.CallFoo(S: string; I: Integer);
{ Calls JavaScript Foo() function }
var
Doc: IHTMLDocument2; // current HTML document
HTMLWindow: IHTMLWindow2; // parent window of current HTML document
JSFn: string; // stores JavaScipt function call
begin
// Get reference to current document
Doc := WebBrowser1.Document as IHTMLDocument2;
if not Assigned(Doc) then
Exit;
// Get parent window of current document
HTMLWindow := Doc.parentWindow;
if not Assigned(HTMLWindow) then
Exit;
// Run JavaScript
try
JSFn := Format('Foo(''%s'',%d)', [S, I]); // build function call
HTMLWindow.execScript(JSFn, 'JavaScript'); // execute function
except
// handle exception in case JavaScript fails to run
end;
end;
type
TForm1 = class(TForm)
btnCallJS: TButton;
cmbFonts: TComboBox;
WebNav: TWebBrowser;
procedure FormShow(Sender: TObject);
procedure WebNavDocumentComplete(Sender: TObject;
const pDisp: IDispatch; var URL: OleVariant);
procedure btnCallJSClick(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
procedure TForm1.FormShow(Sender: TObject);
begin
// Disable button
btnCallJS.Enabled := false;
// Load the Html page
WebNav.Navigate(ExtractFilepath(Application.ExeName)
+'test.html');
end;
procedure TForm1.WebNavDocumentComplete(Sender: TObject;
const pDisp: IDispatch; var URL: OleVariant);
begin
// When complete loading Html page, enable button
btnCallJS.Enabled := true;
end;
// Call the Javascript in Html page
procedure TForm1.btnCallJSClick(Sender: TObject);
var
// current Html document
Doc : IHtmlDocument2;
// parent window of current Html document
HtmlWnd : IHtmlWindow2;
// Javascript function name including arguments
JsFnc : string;
begin
// Get reference to current document
Doc := WebNav.Document as IHtmlDocument2;
if not assigned(Doc) then
exit;
// Get parent window of current Html document
HtmlWnd := Doc.parentWindow;
if not assigned(HtmlWnd) then
exit;
// Run Javascript
try
JsFnc := 'SetFont(''' + trim(cmbFonts.Text) + ''')';
HtmlWnd.execScript(JsFnc, 'JavaScript');
except
Showmessage('Call JavaScript failed!');
end;
end;