Wednesday, January 5, 2011

Stopping TWebBrowser Errors On GoBack And GoForward

unit Unit1;

interface

uses
  Windows, Messages, SysUtils, Classes, Controls, Forms,
  OleCtrls, SHDocVw, StdCtrls;

type
  TForm1 = class(TForm)
    WebBrowser1: TWebBrowser;
    ButtonGoBack: TButton;
    ButtonGoForward: TButton;
    procedure FormShow(Sender: TObject);
    procedure WebBrowser1CommandStateChange(Sender: TObject;
      Command: Integer; Enable: WordBool);
    procedure ButtonGoBackClick(Sender: TObject);
    procedure ButtonGoForwardClick(Sender: TObject);

  private
    { Private declarations }
  public
    { Public declarations }
  end;

var
  Form1: TForm1;

implementation

{$R *.DFM}

procedure TForm1.FormShow(Sender: TObject);
begin
  WebBrowser1.Navigate('http://www.someurl.com');
end;

procedure TForm1.WebBrowser1CommandStateChange(Sender: TObject;
  Command: Integer; Enable: WordBool);
begin
  case Command of
    CSC_NAVIGATEBACK: ButtonGoBack.Enabled := Enable;
    CSC_NAVIGATEFORWARD: ButtonGoForward.Enabled := Enable;
  end;
end;

// Important: Set this button initially with enabled = false
procedure TForm1.ButtonGoBackClick(Sender: TObject);
begin
  WebBrowser1.GoBack;
end;

// Imporant: Set this button initially with enabled = false
procedure TForm1.ButtonGoForwardClick(Sender: TObject);
begin
  WebBrowser1.GoForward;
end;

end.


With TWebBrowser's GoBack and GoForward, an 'unspecified error' will be thrown if there is no backward or forward history to which to navigate.
This simple solution uses TWebBrowser's CommandStateChange event to grab the history flags in a case statement, enabling the back and forward buttons only when appropriate.
Remember to set the enabled state to false on the buttons, initially!

Twitter Delicious Facebook Digg Stumbleupon Favorites More

 
Design by Kang Iwan K-sev | Thank's for your visit To My Site - Ridwan Mulyana | Cibeureum