Opening TWebBrowser link in default browser

Bogdan Botezatu picture Bogdan Botezatu · Jul 19, 2012 · Viewed 8.8k times · Source

My application displays a small banner loaded from the web in a TWebBrowser control. This banner is actually a HTML page including an image; when the users click the image it takes them to the promotional campaign we're currently running.

The bad thing here is that when clicking the link in TWebBrowser, the campaign page is opened in Internet Explorer, not in their default browser. I know this happens because TWebBrowser is a IE-based control, but is there a way to open the link in users' browser of choice?

Thank you.

Answer

Remy Lebeau picture Remy Lebeau · Jul 20, 2012

In the OnBeforeNavigate2 event, check the requested URL and if it is one that you want to launch then Stop() the current navigation and call ShellExecute() to launch the URL in the user's default external browser.

procedure TForm1.WebBrowser1BeforeNavigate2(Sender: TObject; pDisp: IDispatch; var URL: Variant; var Flags: Variant; var TargetFrameName: Variant; var PostData: Variant; var Headers: Variant; var Cancel: WordBool);
begin  
  if (URL should be launched) then
  begin
    Cancel := True;
    WebBrowser1.Stop;
    ShellExecute(0, nil, PChar(String(Url)), nil, nil, SW_SHOWNORMAL);
  end;
end;