Handling hardware back button and sending it to WebBrowser control running on Windows Phone

后端 未结 2 1572
眼角桃花
眼角桃花 2020-12-17 01:23

I have a web browser control embedded into a PhoneApplicationPage. I have to handle the hardware back button and force the web browser to go back.

I know how to hand

2条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-17 02:13

    I've just handled this same question inside Overflow7

    I decided to handle this in C# rather than in Javascript. Basically, in my page I've added a stack of Uri's:

        private Stack NavigationStack = new Stack();
    

    then I've intercepted the Navigated event of the web browser:

        void TheWebBrowser_Navigated(object sender, System.Windows.Navigation.NavigationEventArgs e)
        {
            NavigationStack.Push(e.Uri);
        }
    

    then in the back key press override I try to navigate using the back button if I can:

        protected override void OnBackKeyPress(System.ComponentModel.CancelEventArgs e)
        {
            if (NavigationStack.Count > 1)
            {
                // get rid of the topmost item...
                NavigationStack.Pop();
                // now navigate to the next topmost item
                // note that this is another Pop - as when the navigate occurs a Push() will happen
                TheWebBrowser.Navigate(NavigationStack.Pop());
                e.Cancel = true;
                return;
            }
    
            base.OnBackKeyPress(e);
        }
    

    Note that this solution doesn't work perfectly with tombstoning - nor with "ajax" sites - but overall it seems to work pretty well.

提交回复
热议问题