Using Microsoft Edge in a native Windows desktop app – part 3

This article has been updated for the new version of WebView2 that requires Microsoft Edge 82.0.488.0 or newer.

In the previous article, we learned how to create a web view and display web content in a Windows desktop application. In this third article of the series, we will look in detail at navigation and handling events, in general.

Articles in this series:

Navigation overview

To navigate to a web URL you must use the method Navigate() from the ICoreWebView2 interface. The only argument this method takes is the URL of the web page. However, you must specify the scheme, such as http:// or https:// or file://. URLs of the form www.bing.com or simply bing.com do not work. For this reason, in the code shown in the previous article, you can see this helper method for navigating:

What is happening here, we look if the URL contains ://. If it does not, but it starts with something like C: then we prefix it with file://, otherwise with http://.

During navigation, the web view control generates several events, as follows:

(Source: docs.microsoft.com)

NavigationStarting is the first event, generated when navigation begins. If HTTP redirection occurs, then multiple NavigationStarting events will be fired. When navigation completes, the event NavigationCompleted is fired. In between these, SourceChanged, ContentLoading, and HistoryChanged events may be generated.

You can learn more about navigation events here.

If you want to display some HTML content that you have locally, or generated on the fly, and you do not actually need to go to the web, you can use the method NavigateToString() that will display the HTML content provided as a string.

Handling navigation events

To handle web content events, you must register handlers. You can do this using the ICoreWebView2 interface. For instance, to handle NavigationStarting and NavigationCompleted, call add_NavigationStarting and add_NavigationCompleted. If you no longer wish to handle these events, you can remove the handlers by calling remove_NavigationStarting and remove_NavigationCompleted.

The same approach for registering and unregistering event handlers applies to all events. For an event X there is an add_X() and remove_X() pair of methods to add and remove handlers.

You can only register events after the web view control has been created and you have a valid pointer to the ICoreWebView2 interface. In the sample application, and the code shown in the previous article, the method OnCreateWebViewCompleted() contained a call to RegisterEventHandlers(). In this method, we add the handlers for the two navigation events.

The functions add_NavigationStarting() and add_NavigationCompleted, as well as the other event handler registration methods, take two arguments: the first is a pointer to a callback that is invoked when the event occurs, and the second is a pointer to a EventRegistrationToken object, which represent a reference to a delegate (the callback) that receives change notifications. This token is set by the function and must be passed to the method that removes the event handler. In other words, the token received from add_NavigationStarting() must be passed to remove_NavigationStarting() in order to be able to remove the event handler.

What we do in the event handlers above is the following. At the start of the navigation, we only set a Boolean flag that indicates that the navigation is in progress. We need this for instance if we want to have a button that we can press to stop loading a page if that takes too long. At the end of the navigation, the flag is reset but we also invoke a callback, if any was set by the caller when starting the navigation. In the demo app, we use a callback for the navigation completion from the main frame in order to update the URL in the toolbar with the URL resulted after the navigation, which may not be the original one (because HTTP redirects can occur).

In the previous article, we saw a method called CloseWebView() what closed the web view control. Here is the method updated with removing handlers for the navigation events.

Handling other events

Let us look at another example for handling events. For this purpose we will consider the DocumentTitleChanged event that is occurring when the DocumentTitle property of the web view changes. This may occur before or after the NavigationCompleted event. To add/remove a handler for this event, you need a pointer to the ICoreWebView2 interface.

We can handle this event as follows, by adding a handler in the RegisterEventHandlers method we saw above.

What we do here, is retrieving the title of the document and storing it in the class. Then, if a callback was set for this event we invoke it. We can modify the creation of the web view and install a callback for this event so that every time a page is loaded and the title changes we update the title of the main window of the application.

List of events

Currently, the following events can be handled.

Event Description Add/Remove handlers
AcceleratorKeyPressed Fires when an accelerator key or key combo is pressed or released while the WebView is focused add_AcceleratorKeyPressed
remove_AcceleratorKeyPressed
ContainsFullScreenElementChanged An HTML element inside the WebView is entering fullscreen to the size of the WebView or leaving fullscreen add_ContainsFullScreenElementChanged
remove_ContainsFullScreenElementChanged
ContentLoading Fires before any content is loaded, including scripts added with AddScriptToExecuteOnDocumentCreated add_ContentLoading
remove_ContentLoading
DocumentTitleChanged Fires when the DocumentTitle property of the WebView changes. add_DocumentTitleChanged
remove_DocumentTitleChanged
FrameNavigationCompleted Fires when a child frame has completely loaded (body.onload has fired) or loading stopped with error. add_FrameNavigationCompleted
remove_FrameNavigationCompleted
FrameNavigationStarting Fires when a child frame in the WebView requesting permission to navigate to a different URI. add_FrameNavigationStarting
remove_FrameNavigationStarting
GotFocus Fires when WebView got focus. add_GotFocus
remove_GotFocus
LostFocus Fires when WebView lost focus. add_LostFocus
remove_LostFocus
MoveFocusRequested Fires when the user tries to tab out of the WebView. add_MoveFocusRequested
remove_MoveFocusRequested
NavigationCompleted Fires when the WebView has completely loaded (body.onload has fired) or loading stopped with error. add_NavigationCompleted
remove_NavigationCompleted
NavigationStarting Fires when the WebView main frame is requesting permission to navigate to a different URI add_NavigationStarting
remove_NavigationStarting
NewWindowRequested Fires when content inside the WebView requested to open a new window, such as through window.open. add_NewWindowRequested
remove_NewWindowRequested
PermissionRequested Fires when content in a WebView requests permission to access some privileged resources. add_PermissionRequested
remove_PermissionRequested
ProcessFailed Fires when a WebView process terminated unexpectedly or become unresponsive. add_ProcessFailed
remove_ProcessFailed
HistoryChange Listen to the change of navigation history for the top level document. add_HistoryChanged
remove_HistoryChanged
ScriptDialogOpening Fires when a JavaScript dialog (alert, confirm, or prompt) will show for the webview. add_ScriptDialogOpening
remove_ScriptDialogOpening
SourceChanged Fires when the Source property changes. add_SourceChanged
remove_SourceChanged
WebMessageReceived Fires when the IsWebMessageEnabled setting is set and the top level document of the webview calls window.chrome.webview.postMessage. add_WebMessageReceived
remove_WebMessageReceived
WebResourceRequested Fires when the WebView is performing an HTTP request to a matching URL and resource context filter that was added with AddWebResourceRequestedFilter. add_WebResourceRequested
remove_WebResourceRequested
WindowCloseRequested Fires when content inside the WebView requested to close the window, such as after window.close is called. add_WindowCloseRequested
remove_WindowCloseRequested
ZoomFactorChanged Fires when the ZoomFactor property of the WebView changes, either because the caller modified the ZoomFactor property, or due to the user manually modifying the zoom. add_ZoomFactorChanged
remove_ZoomFactorChanged

Try the app

You can download, build, and try the sample app for this series from here: MfcEdgeDemo.zip (222 downloads) .

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.