CWebBrowser2 (MFC) GoBack method causing crash when it has nothing to go back to

197 views Asked by At

My application supports the IE (InternetExplorer) browser. When the back/forward buttons are clicked and there is nothing to go back or forward to, Webbrowser.GoBack() and Webbrowser.GoForward() are causing a crash.

Is there any way to know if I can go back before I actually call GoBack()? I took a look at the CWebBrowser2 class functions, but I couldn't find anything as such.

Is there any API to help on this, or any alternative approach to handle this?

1

There are 1 answers

0
Remy Lebeau On

Is there any way to know if I can go back before I actually call GoBack()?

Per the IWebBrowser2::GoBack() documentation:

Use the DWebBrowserEvents2::CommandStateChange event to check the enabled state of backward navigation. If the event's CSC_NAVIGATEBACK command is disabled, the beginning of the history list has been reached, and the IWebBrowser2::GoBack method should not be used.

And likewise in the IWebBrowser2::GoForward documentation:

Use the DWebBrowserEvents2::CommandStateChange event to check the enabled state of forward navigation. If the event's CSC_NAVIGATEFORWARD command is disabled, the end of the history list has been reached, and the IWebBrowser2::GoForward method should not be used.

And per this discussion thread:

Create a couple of BOOL member variables in the class that processes the ON_UPDATE_COMMAND_UI notifications for the 'back' and 'forward' toolbar buttons -- one for each button state. Initialize them both to FALSE in the ctor. Handle the OnCommandStateChange event, and watch for the CSC_NAVIGATEBACK and CSC_NAVIGATEFORWARD values in the 'nCommand' parameter. When you get the CSC_NAVIGATEBACK value store the 'Enable' parameter value into your BOOL member variable for the 'back' button state. Do the same thing for the 'forward' button state variable when you get CSC_NAVIGATEFORWARD value. In your OnUpdateButtonForward and OnUpdateButtonBack handlers, call pCmdUI->Enable using the corresponding button state member variable.

So, use the browser's CSC_NAVIGATE... state changes to know when it is safe to call GoBack()/GoForward()`. These are the same events that IE uses to enable/disable its own Back/Forward UI toolbar buttons.