使用InvokeScript更改C#变量

我需要检查我的Windows Phone应用程序中的WebBrowser控件是否有历史记录,以及我想办法如何做到这一点的方法是使用browser.InvokeScript("eval", "if(history.length > 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#代码中的导航来解决这个问题:

 ///  /// 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. ///  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/

 hasHistory = (bool)browser.InvokeScript("eval", "return (history.length > 0);"); 

InvokeScript方法返回一个object ,该对象是您执行的脚本返回的object

以下代码有点hackish,但似乎在大多数情况下都能正常工作。

  bool hasHistory = false; try { webBrowser1.InvokeScript("eval"); hasHistory = true; } catch (SystemException ex) { hasHistory = false; }