Good to know recipes about WebView

WebView is a powerful UI component. It was extended in UWP with new features, which give developers more control on content rendering. I would like to highlight some of them, which I found useful.

Execution mode.

When your app is launched at desktop, WebView loads and renders html content in the UI thread. When it’s a mobile device, then html content is processed in a separated thread. If you want to override this behavior and host WebView in a non UI thread at desktop, then you need to set WebView.DefaultExecutionMode to SeparateThread value. WebView.DefaultExecutionMode is a static getter. And the only one way to set a value for that is to pass it into a constructor. So, no way to declare DefaultExecutionMode in XAML. You need to create WebView in code behind and add it to the root panel:

Navigate with custom headers.

WebView.NavigateWithHttpRequestMessage method allows to send a request with a custom http message. This object provides the access to a request headers and content:

Only GET and POST requests can be send with WebView.NavigateWithHttpRequestMessage.

Catch and modify a request.

Every time WebView starts to load html document, it raises NavigationStarting event. At this point, it’s possible to cancel the navigation by setting Cancel property of the event arguments to true. You can use this event to catch an http GET request, add your custom headers or parameters and send it again:

In the handler you can’t access a request body, so it can be applied only for a GET. There is no way to modify POST or DELETE requests.

Handle a deep link.

UI in your app can mix html content with native pages. And navigation between html pages and native content can be done with help of mobile deep linking. In order to provide smooth experience for users, you have to handle deep links gracefully. WebView fires UnsupportedUriSchemeIdentified event, when it can’t process an URI scheme. Just subscribe for the event and process a navigation URI manually.


Leave a Reply