Title: How to create an OnLinkClick-Event in TWebBrowser
Question: The TWebBrowser-object is a great way to display offline html-files
within your application. Sometimes it would be nice to react
within your delphi-application when the user clicks on a link in
the html-view...
Answer:
The answer is really easy actually. It is allready provided in the component TWebBrowser. The event you should react to is called "WebBrowser1BeforeNavigate2".
You can react to this event to change the location URL, or interfere in another way. You can even cancel the oncomming navigation or change the way it is presented to your user, by displaying it in another window for example...
Following is the code based on a form with two components on it:
- A TButton component
- A TWebbrowser component
To try the example put the following code in the corresponding eventhandlers of those two components and here it is... your own OnLinkKlick event :-)
HAVE FUN...
=Code goes here=============================================================
var
Form1: TForm1;
NoUserNavigation: Boolean;
implementation
procedure TForm1.Button1Click(Sender: TObject);
begin
// Initiate a navigation in code, the htm-file in this example could be
// ANY htm-file as long as it contains a link on which you can interfere.
// In this case this is an Off-Line htm-file on my local harddisk, replace
// it with yours...
NoUserNavigation := True;
WebBrowser1.Navigate('C:\test.htm');
end;
procedure TForm1.WebBrowser1BeforeNavigate2(Sender: TObject;
const pDisp: IDispatch; var URL, Flags, TargetFrameName, PostData,
Headers: OleVariant; var Cancel: WordBool);
begin
// Display a message telling you the name of the URL, but only if it is NOT activated by the USER
if NoUserNavigation then
begin
NoUserNavigation := False;
ShowMessage('Navigating to: ' + URL);
end
else
begin
ShowMessage('No user navigation allowed');
Cancel := True;
end;
end;
=Code ends here============================================================