处理硬件后退按钮并将其发送到在Windows Phone上运行的WebBrowser控件

Mug*_*nth 6 .net webbrowser-control windows-phone-7

我有一个嵌入PhoneApplicationPage的Web浏览器控件.我必须处理硬件后退按钮并强制Web浏览器返回.

知道如何处理硬件后退按钮.

你如何强迫webbrowser转到上一页?看似简单的GoBack()CanGoBack财产上的WinForms网页浏览器似乎缺少在Windows Phone.

Stu*_*art 9

我刚刚在Overflow7中处理了同样的问题

我决定用C#而不是Javascript来处理这个问题.基本上,在我的页面中,我添加了一堆Uri:

    private Stack<Uri> NavigationStack = new Stack<Uri>();
Run Code Online (Sandbox Code Playgroud)

然后我截获了Web浏览器的Navigated事件:

    void TheWebBrowser_Navigated(object sender, System.Windows.Navigation.NavigationEventArgs e)
    {
        NavigationStack.Push(e.Uri);
    }
Run Code Online (Sandbox Code Playgroud)

然后在后退键按下覆盖我尝试使用后退按钮导航,如果我可以:

    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);
    }
Run Code Online (Sandbox Code Playgroud)

请注意,此解决方案不能与墓碑完美配合 - 也不能与"ajax"站点完美配合 - 但总体而言,它似乎运行良好.


Der*_*kin 4

如果WebBrowser通过设置在控件上启用脚本IsScriptEnabled="true",则可以使用以下命令在浏览器中向后导航:

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

您可以在 Shaw Wildermuth 的博客文章Navigating with the WebBrowser Control on WP7中找到此代码(以及更多代码)。