c# - 使用 InvokeScript 更改 C# 变量

标签 c# javascript windows-phone-7

我需要检查我的 Windows Phone 应用程序中的 WebBrowser 控件是否有历史记录,我想出如何做到这一点的方法是使用 browser.InvokeScript("eval", "if(history.长度 > 0){ history.go(-1) }");。我需要使用此方法或其他方法来设置变量,以便仅当 WebBrowser 有历史记录时我才能触发函数。我不知道如何设置它。

我使用的完整代码是这样的:

protected override void OnBackKeyPress(System.ComponentModel.CancelEventArgs e)
        {

            var hasHistory = true;

            browser.InvokeScript("eval", "if(history.length > 0){ history.go(-1) }");

            if (AppSettings.Default.ExitWarning)
            {
                if (!hasHistory) {                    
                    if (MessageBox.Show("Are you sure you want to exit?", "Exit?",  MessageBoxButton.OKCancel) != MessageBoxResult.OK)
                    {
                        e.Cancel = true;
                    }
                }
            }
        }

最佳答案

恐怕您的方法有缺陷! history.length 值不能用于指示您所在的页面。如果您向前导航然后向后导航,历史长度将为 2 以允许向前导航。

我通过在 C# 代码中跟踪导航解决了这个问题:

/// <summary>
/// Handles the back-button for a PhoneGap application. When the back-button
/// is pressed, the browser history is navigated. If no history is present,
/// the application will exit.
/// </summary>
public class BackButtonHandler
{
  private int _browserHistoryLength = 0;
  private PGView _phoneGapView;

  public BackButtonHandler(PhoneApplicationPage page, PGView phoneGapView)
  {
    // subscribe to the hardware back-button
    page.BackKeyPress += Page_BackKeyPress;

    // handle navigation events
    phoneGapView.Browser.Navigated += Browser_Navigated;

    _phoneGapView = phoneGapView;
  }

  private void Browser_Navigated(object sender, NavigationEventArgs e)
  {
    if (e.NavigationMode == NavigationMode.New)
    {
      _browserHistoryLength++;
    }
  }

  private void Page_BackKeyPress(object sender, CancelEventArgs e)
  {
    if (_browserHistoryLength > 1)
    {
      _phoneGapView.Browser.InvokeScript("eval", "history.go(-1)");
      _browserHistoryLength -= 2;
      e.Cancel = true;
    }
  }
}

如这篇博文所述:

http://www.scottlogic.co.uk/blog/colin/2011/12/a-simple-multi-page-windows-phone-7-phonegap-example/

关于c# - 使用 InvokeScript 更改 C# 变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8611834/

相关文章:

C# - 从子类中获取属性值

c# - 将 Cmd 命令传递给 C# 应用程序

javascript - 如何将此 Object.values 除以总数?

javascript - 使用 Protractor 使用部分文本来控制重定向

windows-phone-7 - WP7 Mango 中的列表框是否默认虚拟化?

c# - 对象引用未设置到对象实例,在 WPF 设计器中,位于 x :Reference

c# - 希腊语的mysql字段可以在 Crystal 报表中显示吗?

javascript - 在另一个div上显示溢出的文本部分

windows-phone-7 - WP7 - 从前台应用程序控制 BackgroundAudioPlayer

windows-phone-7 - Windows Phone 7 Listbox ArrangeOverride 无法使用?