The WebBrowser control adds browsing, document viewing, and data downloading capabilities to your applications. Applications using this control will allow the user to browse sites on the Internet's World Wide Web, as well as folders in the local file system and on a network. The WebBrowser control supports Web browsing through both point-and-click hyperlinking and Uniform Resource Locator (URL) navigation. The control maintains a history list that allows the user to browse forward and backward through previously browsed sites, folders, and documents.
The actual parsing and rendering of the HTML documents in the WebBrowser control is handled by the Mshtml.dll component of Microsoft® Internet Explorer 4.0, or 5. The MSHTML component is an Active Document (also known as an OLE document object) that provides support for parsing and rendering with the Dynamic HTML Object Model, as well as for hosting ActiveX® Controls and scripts. The WebBrowser control directly handles the navigation, hyperlinking, history lists, favorites, and security. Applications can also use the WebBrowser control as an Active Document container to host other Active Documents. This means that richly formatted documents, such as a Microsoft® Excel spreadsheet or Microsoft® Word document, can be opened and edited in-place from within the WebBrowser control. WebBrowser is also an ActiveX control container that can host any ActiveX control.
For Internet Explorer 4.0, the following new properties, methods, and events have been added:
Visual Basic | C/C++ | Type | Description |
AddressBar | get_AddressBar | property | Indicates whether the URL address bar is shown. |
Offline | get_Offline | property | Determines if the browser is in offline mode. |
ReadyState | get_ReadyState | property | Returns the OLE ReadyState bindable object. |
RegisterAsBrowser | get_RegisterAsBrowser | property | Indicates whether the WebBrowser control is registered as a top-level browser. |
RegisterAsDropTarget | get_RegisterAsDropTarget | property | Indicates whether the WebBrowser control is registered as a drop target. |
Resizable | get_Resizable | property | Indicates whether the Internet Explorer object can be resized. |
Silent | get_Silent | property | Indicates whether dialog boxes can be shown. |
TheaterMode | get_TheaterMode | property | Indicates whether the browser is in "Theater Mode" or a normal browser window. |
ExecWB | ExecWB | method | Executes an IOLECommandTarget interface command. |
Navigate2 | Navigate2 | method | Navigates the WebBrowser control to a URL. |
QueryStatusWB | QueryStatusWB | method | Returns the status of commands using the IOLECommandTarget interface. |
ShowBrowserBar | ShowBrowserBar | method | Shows or hides a browser bar. |
BeforeNavigate2 | BeforeNavigate2 | event | Occurs before the WebBrowser control navigates to a new URL. (replaces BeforeNavigate and FrameBeforeNavigate) |
DocumentComplete | DocumentComplete | event | Occurs when the ReadyState property is changed to READYSTATE_COMPLETE. |
NavigateComplete2 | NavigateComplete2 | event | Occurs after the WebBrowser control navigates to a new URL (replaces NavigateComplete and FrameNavigateComplete). |
NewWindow2 | NewWindow2 | event | Occurs when navigation occurs with the navOpenInNewWindow flag (replaces NewWindow and FrameNewWindow). |
OnFullScreen | OnFullScreen | event | Occurs when the FullScreen property changes. |
OnMenuBar | OnMenuBar | event | Occurs when the MenuBar property changes. |
OnQuit | OnQuit | event | Occurs before the Internet Explorer application quits. |
OnStatusBar | OnStatusBar | event | Occurs when the StatusBar property changes. |
OnTheaterMode | OnTheaterMode | event | Occurs when the TheaterMode property changes. |
OnToolBar | OnToolBar | event | Occurs when the ToolBar property changes. |
OnVisible | OnVisible | event | Occurs when the Visible property changes. |
The new WebBrowser_V1 object is now included with the WebBrowser control. This object supports the set of properties, methods, and events that exist in Internet Explorer 3.0. You can use the WebBrowser_V1 object in a Visual Basic project to run on computers with either Internet Explorer 3.0 or 4.0, or 5 installed. The WebBrowser object requires Internet Explorer 4.0, or 5 to access the new properties, methods, and events listed above.
The WebBrowser control supports properties, methods, and events that allow developers to create a highly customized Web browser with the WebBrowser object. Companies may want to use the WebBrowser control to create a Web browsing application that restricts navigation to a local intranet and company-approved public Web sites.
An application can also create and manipulate an instance of the Internet Explorer application through OLE Automation with the InternetExplorer object. In this context, additional properties and methods not supported by the WebBrowser object are available. These additional features are indicated in the Applies To list for the InternetExplorer object only. If these features are used with the WebBrowser object, error codes will be returned. Errors can be trapped in Visual Basic with the "On Error Resume Next" statement and by accessing the Err object's associated properties such as Err.Number and Err.Description.
To implement the InternetExplorer object in a Visual Basic application, declare the object as indicated in the Application property description. To use the WebBrowser object, simply add the "Microsoft Internet Controls" to your Visual Basic project and place the WebBrowser control on a Visual Basic form. This is accomplished by selecting the "Components..." item on the Project menu in Visual Basic 5.0, or by selecting the "Custom Controls..." item on the Tools menu in Visual Basic 4.0, or 5.
Many properties can be used to retrieve information about the WebBrowser control. The LocationName and LocationURL properties can be used to retrieve information about the location that is currently displayed. If the location is an HTML page on the World Wide Web, LocationName retrieves the title of that page, and LocationURL retrieves the URL of that page. If the location is a folder or file on the network or local computer, LocationName and LocationURL both retrieve the Universal Naming Convention (UNC) name or the full path of the folder or file.
The current status of the WebBrowser control can be obtained using the Busy property. This Boolean value indicates whether the control is engaged in a navigation or downloading operation. You should check the value of this property before issuing the Stop method to cancel navigation or downloading operations.
The WebBrowser control supports properties and associated events to manipulate various user interface elements of an Internet Explorer application or a custom browser. The size and position of the window used by the WebBrowser control can be read or set with the Height, Left, Top, and Width properties. Other user interface elements are enabled with individual properties such as MenuBar, FullScreen, StatusBar, and ToolBar. The associated OnMenuBar, OnFullScreen, OnStatusBar, and OnToolBar events are triggered when the property value changes. These events return a Boolean value to indicate the new state of the property and to provide a mechanism to respond to user actions in the InternetExplorer object.
When using OLE Automation with the InternetExplorer object, the application window can be shown or hidden by setting the value of the Visible property. When changed, the associated OnVisible event returns the current Boolean value of the property. You may also want to retrieve information about the Internet Explorer application itself. To do so, use the Name property to get the Internet Explorer application name, and use the Path and FullName properties to get the Internet Explorer application's path and file name.
Use the Navigate or Navigate2 method to browse HTML pages on the World Wide Web or any file or folder on the network or local computer. In addition to the required URL argument passed to the Navigate or Navigate2 method, you can optionally include flags to specify more detailed information about the navigation, such as the HTML frame name target and the HTTP headers sent to the server. You can browse through the sites maintained in the browser's history list during each browser session by using the GoBack and GoForward methods. If you wish to go directly to the Internet Explorer home or search pages that have been specified in the Internet Explorer Options dialog box, use the GoHome or GoSearch method. To display the most current version of a page the browser is viewing, use the Refresh or Refresh2 method. When using OLE Automation, call the Quit method to close the instance of the Internet Explorer application.
The WebBrowser control triggers a number of different events to notify an application of user- and browser-generated activity. When the browser is about to navigate to a new location, it triggers a BeforeNavigate2 event that specifies the URL or path of the new location and any other data that will be transmitted to the Internet server through the HTTP transaction. The data can include the HTTP header, HTTP post data, and the URL of the referrer. The BeforeNavigate2 event also includes a flag that can be set to cancel the pending navigation request. This event can be useful for checking the requested URL against a database of unauthorized World Wide Web sites or local and network folders, and for canceling the navigation request. The WebBrowser control fires the NavigateComplete2 event after it has navigated to a new location. This event includes the same information as BeforeNavigate2, except NavigateComplete2 does not include the cancel flag.
Whenever the browser is about to begin a download operation, it triggers the DownloadBegin event. The control also generates a number of ProgressChange events as the operation progresses, and then it triggers the DownloadComplete event after completing the operation. Applications typically use these three events to indicate the progress of the download operation, often by displaying a progress bar. An application would show the progress bar in response to DownloadBegin, update the progress bar in response to ProgressChange, and hide the progress bar in response to DownloadComplete.
When an application calls the Navigate or Navigate2 method with the navOpenInNewWindow flag, the NewWindow2 event occurs before the new browser window is created. This event allows the application to create the new browser window or have a new instance of the Internet Explorer application created. Once the new window is created, an accompanying BeforeNavigate2 event occurs.
Note The events discussed in the preceding section that apply to the InternetExplorer object are supported in Visual Basic version 5.0 and later.
Suppose you want to create a custom browser application to start and display an HTML page that is not the user's home or start page. You also want the custom browser to navigate only to HTML pages on the local domain or view files on the local hard disk. Here's how you could create this simple application:
Private Sub Form_Load() On Error Resume Next 'Don't stop execution, continue on next line WebBrowser.Navigate2 "http:\\www.xyzcorp.com" If Err.Number <> 0 Then MsgBox "Error :" & Err.Description 'Display error message End Sub
Private Sub WebBrowser_BeforeNavigate2(ByVal URL As String, ByVal Flags As Long, ByVal TargetFrameName As String, PostData As Variant, ByVal Headers As String, Cancel As Boolean) If (Instr(1,URL,"xyzcorp.com") = 0) And (Instr(1,URL,"C:") = 0) Then Cancel = True MsgBox "Access denied to URL: " & URL End If End Sub
The WebBrowser control supports several common file operationssuch as Print, Print Preview, Save, Save As, New, and Propertieswith the QueryStatusWB and ExecWB methods. These methods directly access the IOleCommandTarget interface for issuing commands on the Active Document or inquiring about which commands it supports. The following example shows the implementation of a Print command button that, when clicked, checks to make sure the Print command is valid and then displays the print dialog box for the WebBrowser control.
Private Sub BtnPrint_Click() Dim eQuery As OLECMDF 'return value type for QueryStatusWB On Error Resume Next eQuery = WebBrowser1.QueryStatusWB(OLECMDID_PRINT) 'get print command status If Err.Number = 0 Then If eQuery And OLECMDF_ENABLED Then WebBrowser1.ExecWB OLECMDID_PRINT, OLECMDEXECOPT_PROMPTUSER, "", "" 'Ok to Print? Else MsgBox "The Print command is currently disabled." End If End If If Err.Number <> 0 Then MsgBox "Print command Error: " & Err.Description End Sub
When using OLE Automation to control a separately running instance of an application, you will need to create a mechanism to respond to events triggered by that ActiveX object. To create this mechanism, commonly referred to as an event sink, use the following steps as a guideline.
Public WithEvents m_oWbSink As SHDocVw.InternetExplorer
Private Sub m_oWbSink_StatusTextChange(ByVal Text As String) Form1.txtStatus.Text = Text End Sub
'Global reference to an instance of the browser Dim g_oIE As New SHDocVw.InternetExplorer 'Global reference to an instance of a class that can sink the browser's events Dim g_oIESink As New Class1
Set g_oIESink.m_oWbSink = g_oIE
Note The preceding steps are unnecessary when using the WebBrowser object. Events are automatically trapped when you select the WebBrowser control in the Visual Basic toolbox and place it directly on a form.
This section describes some of the common implementations of the WebBrowser control, including:
One of the most common uses for the WebBrowser control is to add Internet browsing functionality to your application. Using the IWebBrowser2 interface, you can browse to any location in the local file system, on the network, or on the World Wide Web. You can use the Navigate method to tell the control which location to browse to. The first parameter is a string that contains the name of the location. To browse to a location in the local file system or on the network, specify the full path to the file system location or the Universal Naming Convention (UNC) name of the location on the network. To browse to a site on the World Wide Web, specify the URL of the site. By including a text box in your application, you can let the user specify the location to browse to and then pass the location to the Navigate method.
In this example, the WebBrowser control was inserted into a basic Microsoft Foundation Class Library (MFC) application. A class was added to the project, and the control was dynamically created in the OnCreate handler of the application's View class.
CRect rect; GetClientRect (&rect); // Create the control. m_pBrowser = new CWebBrowser; ASSERT (m_pBrowser); if (!m_pBrowser->Create(NULL,NULL,WS_VISIBLE,rect,this,NULL)) { TRACE("failed to create browser\n"); delete m_pBrowser; m_pBrowser = NULL; return 0; } // Initialize the first URL. COleVariant noArg; m_pBrowser->Navigate("www.microsoft.com",&noArg,&noArg,&noArg,&noArg); return 0;
In addition, the Navigate method allows you to target a specific frame on an HTML page, causing the WebBrowser control to display a Web site or file system location in that frame. First, you would call the Navigate method and specify the URL of an HTML page that contains a frame. Then, by specifying the name of the frame in subsequent calls to Navigate, you can direct the control to display subsequent locations within that frame.
You can also use the get_LocationName and get_LocationURL methods to retrieve information about the location that the WebBrowser control is currently displaying. If the location is an HTML page on the World Wide Web, get_LocationName retrieves the title of that page, and get_LocationURL retrieves the URL of that page. If the location is a folder or file on the network or local computer, get_LocationName and get_LocationURL both retrieve the UNC or full path of the folder or file.
Although the WebBrowser control does not support a print method, you can print its contents using one of the following methods:
LPDISPATCH lpDispatch = NULL; LPOLECOMMANDTARGET lpOleCommandTarget = NULL; lpDispatch = m_pBrowser.get_Document(); ASSERT(lpDispatch); lpDispatch->QueryInterface(IID_IOleCommandTarget, (void**)&lpOleCommandTarget); ASSERT(lpOleCommandTarget); lpDispatch->Release(); // Print contents of WebBrowser control. lpOleCommandTarget->Exec(NULL, OLECMDID_PRINT, 0, NULL,NULL); lpOleCommandTarget->Release();
The WebBrowser automation model does not support a method that allows you to change the font of the text of the currently displayed page. However, the WebBrowser control exposes this functionality through the IOleCommandTarget interface. Call the get_Document method, which returns an IDispatch pointer. Using this IDispatch pointer, call QueryInterface on IID_IOleCommandTarget. With this IOleCommandTarget interface pointer, call Exec with OLECMDID_ZOOM and use the pvaIn input argument to pass a value in the range of 0 to 5 (where 0 is smallest), indicating the desired scale of the font. This, in effect, mimics the functionality available through the Internet Explorer Fonts command on the View menu.
LPDISPATCH pDisp = NULL; LPOLECOMMANDTARGET pCmdTarg = NULL; pDisp = m_pBrowser.get_Document(); ASSERT(pDisp); pDisp->QueryInterface(IID_IOleCommandTarget, (LPVOID*)&pCmdTarg); ASSERT(pCmdTarg); VARIANT vaZoomFactor; // input arguments VariantInit(&vaZoomFactor); V_VT(&vaZoomFactor) = VT_I4; V_I4(&vaZoomFactor) = fontSize; pCmdTarg->Exec(NULL, OLECMDID_ZOOM, OLECMDEXECOPT_DONTPROMPTUSER, &vaZoomFactor, NULL); VariantClear(&vaZoomFactor); if (pCmdTarg) pCmdTarg->Release(); // release document's command target if (pDisp) pDisp->Release(); // release document's dispatch interface
The WebBrowser control fires a number of different events to notify an application of user- and browser-generated activity. The events are implemented using the DWebBrowserEvents2 interface. When the control is about to navigate to a new location, it fires a BeforeNavigate2 event that specifies the URL or path of the new location and any other data that will be transmitted to the Internet server through the HTTP transaction. The data can include the HTTP header, HTTP post data, and the URL of the referrer. BeforeNavigate2 also includes a cancel flag that you can set to FALSE to cancel the navigation. The WebBrowser control fires the NavigateComplete2 event after it has navigated to a new location. This event includes the same information as BeforeNavigate2, but NavigateComplete2 does not include the cancel flag.
When the WebBrowser control is about to begin a download operation, it fires the DownloadBegin event. The control fires a number of ProgressChange events as the operation progresses, and then it fires the DownloadComplete event after completing the operation. Applications typically use these three events to indicate the progress of the download operation, often by displaying a progress bar. An application would show the progress bar in response to DownloadBegin, update the progress bar in response to ProgressChange, and hide it in response to DownloadComplete.
When an application calls the Navigate method with the Flags parameter set to navOpenInNewWindow, the WebBrowser control fires the NewWindow2 event before navigating to the new location. The event includes information about the new location and a flag that indicates whether the application or the control is to create the new window. Set this flag to TRUE if your application will create the window or to FALSE if the WebBrowser control should create it.
You will need to implement an event sink to capture and handle the various events. An example of how to implement an event sink for DWebBrowserEvents2 can be found in the Objvw sample.
The following topics provide more information about the WebBrowser control.