在 Delphi 中使用 TWebBrowser 控件操作 DOM 時,必須等待頁面完全加載完成才能安全獲取 window 對象。過早嘗試會導致介面查詢失敗或返回空引用,引發存取違規。
TWebBrowser 的 OnDocumentComplete 事件在主文檔(而非框架)加載完畢時觸發。通過判斷 pDisp 參數是否等於瀏覽器的 Application 屬性,可確保僅處理主框架完成的情況。
unit Unit1;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, OleCtrls, SHDocVw, StdCtrls;
type
TForm1 = class(TForm)
WebBrowser1: TWebBrowser;
Button1: TButton;
Button2: TButton;
procedure FormCreate(Sender: TObject);
procedure WebBrowser1DocumentComplete(ASender: TObject;
const pDisp: IDispatch; var URL: OleVariant);
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
uses MSHtml;
var
window: IHTMLWindow2;
{ 建立時同步導航 }
procedure TForm1.FormCreate(Sender: TObject);
begin
WebBrowser1.Align := alTop;
WebBrowser1.Navigate('https://del.cnblogs.com');
end;
{ 頁面加載完畢,安全獲取 window 對象 }
procedure TForm1.WebBrowser1DocumentComplete(ASender: TObject;
const pDisp: IDispatch; var URL: OleVariant);
begin
if pDisp = (ASender as TWebBrowser).Application then
begin
window := ((ASender as TWebBrowser).Document as IHTMLDocument2).parentWindow;
// 此處可安全使用 window 對象操作 DOM
end;
end;
end.
window: IHTMLWindow2 定義在 MSHtml 單元,提供完整的代碼提示支援。pDisp = (ASender as TWebBrowser).Application 確保是主文檔而非 iframe 觸發。Document as IHTMLDocument2 獲取文檔介面,再取 parentWindow 獲得頂層 window。遵循此模式,即可在 Delphi 中穩健地進行後續的 DOM 操作、腳本注入或事件綁定。