Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Opening TWebBrowser link in default browser

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.

like image 580
Bogdan Botezatu Avatar asked Jul 19 '12 08:07

Bogdan Botezatu


2 Answers

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;
like image 154
Remy Lebeau Avatar answered Oct 05 '22 07:10

Remy Lebeau


TWebBrowser exposes DWebBrowserExents2::NewWindow2 via its own NewWindow2 event

So handle the event and provide the automation interface to the event sender

procedure TForm1.WebBrowser1NewWindow2(
    ASender: TObject; var ppDisp: IDispatch; var Cancel: WordBool);

begin  
// create a new browser (e.g. hosted on a new tab /MDI form/ top level window)
// and expose the browser as a property of the new window. 
// Here a form2 object is created to host the new webbrowser instance
...
form2.InitNavigate=False;//the navigation will be triggered after this event
form2.Visible=False;//new window is only for getting the url
ppDisp := form2.WebBrowser1.Application;  
form2.Show;
end;

Now you can get the the new window's URL in the BeforeNavigate2 event handler on form2. Cancel the event and you can use ShellExecute to launch the default browser.

If you only support Windows SP SP2 or higher, you can hook the NewWindow3 event which provide the URL in the arguments before the new window is created.

like image 39
Sheng Jiang 蒋晟 Avatar answered Oct 05 '22 08:10

Sheng Jiang 蒋晟