我们有HTML:
<A target="_blank" href="http://blabla.com">
单击链接后,将触发OnNewWindow2
:
procedure TForm1.WebBrowser1NewWindow2(Sender: TObject;
var ppDisp: IDispatch; var Cancel: WordBool);
begin
Cancel := True;
// open in default browser
end;
我想在默认浏览器中打开链接:Opening TWebBrowser link in default browser
但是在我的案例中没有开除BeforeNavigate2
。如何知道TWebBrowser
OnNewWindow2
事件中的预期URL?
我如何知道TWebBrowser OnNewWindow2事件中的预期URL?
您可以使用DOM的getAttribute method。但是在您加载所需的页面之前,以及在完成此操作之后,请用您自己的页面替换特定事件。参见下面的代码:
uses
...
SHDocVw, MSHTML;
type
TForm1 = class(TForm)
...
// Your auto-generated event handler
procedure WebBrowser1DocumentComplete(ASender: TObject;
const pDisp: IDispatch; const URL: OleVariant);
private
// Your self-written event handlers
procedure New_BeforeNavigate2(ASender: TObject;
const pDisp: IDispatch; const URL, Flags, TargetFrameName, PostData, Headers: OleVariant;
var Cancel: WordBool);
procedure New_NewWindow2(ASender: TObject; var ppDisp: IDispatch; var Cancel: WordBool);
end;
...
// Assign event handler in design-time
procedure TForm1.WebBrowser1DocumentComplete(ASender: TObject; const pDisp: IDispatch;
const URL: OleVariant);
begin
(ASender as TWebBrowser).OnBeforeNavigate2 := New_BeforeNavigate2;
(ASender as TWebBrowser).OnNewWindow2 := New_NewWindow2;
end;
procedure TForm1.New_BeforeNavigate2(ASender: TObject; const pDisp: IDispatch;
const URL, Flags, TargetFrameName, PostData, Headers: OleVariant;
var Cancel: WordBool);
begin
ShowMessage('New URL will be: ' + URL);
Cancel := true;
end;
procedure TForm1.New_NewWindow2(ASender: TObject; var ppDisp: IDispatch; var Cancel: WordBool);
var
S: String;
begin
S := ((TWebBrowser(ASender).Document as IHTMLDocument2).ActiveElement as IHTMLElement).GetAttribute('href', 0);
ShowMessage('New window''s URL is: ' + S);
Cancel := true;
end;
现在,即使发生OnNewWindow2
事件,您也可以获得URL。对于target="_self"
,也有OnBeforeNavigate2
事件处理程序。如果我正确收到您的问题,它应该可以工作。