WebBrowser Application Basics in Windows Phone 8

WebBrowser is a control available in Windows Phone 8 SDK, which is helpful in displaying web pages. In this post we would see about the GoBack and GoForward methods and how to have safe navigation.

As you see in the following image, we have created a windows phone 8 application with the basic Windows Phone App template.

The primary requirement is the WebBrowser control; let’s add one to the application.

The following piece of code states that the Source property of the WebBrowser control is set to the target Url.

Now let’s run the application and you would see that the web page is displayed.

Congratulation on your WebBrowser application. But wait, don’t celebrate too early. Let’s test some scenarios.

Tester’s point of view

  1. The hardware back button exits the application
  2. Cannot come back to previous page with hardware back button
  3. There is no option to go to the immediate next page
  4. There is no option to refresh the page

To achieve a safe browser application, you need to have basic things. Here are they

  1. Back Button for back navigation
  2. Next Button for forward navigation
  3. Refresh Button for reloading the page
  4. Handle the Hardware Back button

To have the back, next and refresh buttons; let’s create custom button controls.

We will not discuss the styling of the controls; you could refer the sample attached for the button styles.

The following image shows that, the navigation and refresh controls are placed in the application.

The XAML of the above is displayed in the following.

The single button click event handler is subscribed. Each button could be identified with its Tag property.

In the above code snippet, you could see that, WebBrowser control has CanGoBack and CanGoForward properties to help navigating back or forward.

To refresh the page, just reassign the Source property.

Also in the following code snippet, we have subscribed to LoadCompleted event. The buttons’ IsEnabled is based on the WebBrowser control’s CanGoBack and CanGoForward properties.

Let’s run the application. You could see that, the buttons are working as expected.

Beware of Hardware Back Button

We need to handle the hardware back button. To achieve that, you need to override the OnBackKeyPress method. You need to be careful with the Cancel property. To Cancel the back press make it true and to enable it make it false.

Now that we have handled the hardware back button press event, we could ago ahead and run the application. The following screens are displayed as expected.

The following navigation shows the way it should behave.

Hope this post helps.

Thanks for reading, keep subscribing to my blog. Like me in Facebook. And Follow in twitter.