Freigeben über


Windows Phone 8.1– Hardware Back Button & WebView

Webview is excellent control to display html contents within your Windows Phone 8.1 Application. One challenge that I came across while working on an app was how to implement Go Back functionality in conjunction with hardware back button. Please note that to maintain a consistent user experience, the Back button must only be used for backwards navigation in the app. The following four requirements are related to use of the hardware back button.

    • Pressing the Back button must return the app to the previous page or return to any previous page within the back stack.
    • Pressing the Back button from the first screen of an app must navigate away from the app to the previous app on the back stack.
    • If the current page displays a context menu or a dialog, the pressing of the Back button must close the menu or dialog and return the user to the screen where the context menu or dialog box was opened.
    • or games, when the Back button is pressed during gameplay, the game can choose to present a pause context menu or dialog, or it can navigate the user to the prior menu screen.

So in light of above requirements, we wanted implement WebView.GoBack() via the hardware back button. Here is the code snippet of how it was implemented

XAML

 <WebView Grid.Row="0" x:Name="MainWebView" Source="https://blogs.msdn.com/ashish"></WebView>

Code Behind

    public BlankPage1()
    {
        this.InitializeComponent();
        Windows.Phone.UI.Input.HardwareButtons.BackPressed += HardwareButtons_BackPressed;
    }
    private void HardwareButtons_BackPressed(object sender, Windows.Phone.UI.Input.BackPressedEventArgs e)
    {
        Frame rootFrame = Window.Current.Content as Frame;
        if (rootFrame != null && rootFrame.CanGoBack && MainWebView.CanGoBack)
        {
            e.Handled = true;
            MainWebView.GoBack();
        }

    }