Title: The OnLinkClick-Event of 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:
A request was put in for an article which will respond to a OnLinkClick.
This article refers to the installed TWebBrowser which comes with Various versions of Delphi. However, for those with versions of Delphi which do not have it installed (eg D2, Standard/Personal Editions), please be aware that it can be installed by ActiveX/OCX importing from shdocvw.dll (this may be called TExplorer, but it is the WebBrowser Control).
Importing can produce slightly different variable names and types from those which Borland hardwires into Delphi. I have steered away from giving the full variable definitions for this reason, however it should all be quite obvious, even to the untrained eye!!
here we go:
The OnLinkClick-Event...
TWebBrowser as an object, unfortunatly, lacks such an event. It's equivalent is the OnBeforeNavigate2. This gives a wealth of information, such as the URL to link to, any various navigation flags and object references, and (really importantly) a chance to cancel the navigation!!
So within an event handler, one could provide custom filtering, eg.
if pos('porn',url)0 then
begin
cancel:=true;
exit;
end;
if pos('pdf',url)0 then
begin
Cancel:= (messagedlg('This will open an Acrobat file. Are you sure you wish to do that?',mtQuestion,[mbOKCancel],0)=mrCancel);
if cancel then exit;
end;
Or whatever is wanted, I will not try to limit the inventive creativities of the D3K members!
If an actual OnLinkClick event is wanted, you could create your own component, decending from TWebBrowser, and include an OnLinkClick event. This could be fired from the OnBeforeNavigate2 (which could be relegated from Published to Public). One could then only give relevant options in the event, and maybe perform other checks. However, This would probably restrict, rather than enhance the functionality of the component - This is one of those occaisons where M$ have done quite a good job on an object!!!
In Conclusion:
Use TWebBrowser.OnBeforeNavigate2 to instagiate any processing in reaction to the user clicking on an anchor/link on an embedded web page.
I have purposely kept this article simple, relevant and functional, to provide easy access for all levels of competancy. For those who wish to investigate the TWebBrowser control, and it's associated joys, please refer to the online help in Delphi, or seach www.microsoft.com for WebBrowser, and be deluged in information!!!!!