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

痴心易碎 提交于 2019-11-27 18:43:30

问题


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 handle hardware back button.

How do you force the webbrowser to go to a previous page? The seemingly simple GoBack() and CanGoBack property on WinForms webbrowser seems to be missing on Windows Phone.


回答1:


If you enable script on the WebBrowser control by setting IsScriptEnabled="true" you can then use the following to navigate backwards within the browser:

private void backButton_Click(object sender, EventArgs e)
{
  try
  {
    browser.InvokeScript("eval", "history.go(-1)");
  }
  catch
  {
    // Eat error
  }
}

You can find this code (and a bit more) in Shaw Wildermuth's blog post Navigating with the WebBrowser Control on WP7.




回答2:


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<Uri> NavigationStack = new Stack<Uri>();

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.



来源:https://stackoverflow.com/questions/5100538/handling-hardware-back-button-and-sending-it-to-webbrowser-control-running-on-wi

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!