2011-12-23 66 views
1

我需要檢查Windows Phone應用程序中的WebBrowser控件是否有歷史記錄,以及我如何解決該問題的方法是使用browser.InvokeScript("eval", "if(history.length > 0){ history.go(-1) }");。我需要使用這個或其他一些方法來設置一個變量,所以我只能在WebBrowser有歷史記錄時才能觸發一個函數。我無法弄清楚如何設置它。使用InvokeScript更改C#變量

我使用完整的代碼是這樣的:

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; 
        } 
       } 
      } 
     } 

回答

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

InvokeScript返回object這是你執行的腳本返回的對象的方法。

下面的代碼有點怪異,但似乎在大多數情況下工作正常。

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

我得到SystemException的80020101當我使用,由於某種原因。任何想法爲什麼? – JacobTheDev

+0

似乎是因爲它無效的JavaScript。我不熟悉直接JS,只是jQuery,返回函數是如何工作的? – JacobTheDev

+1

'eval'是一個JavaScript內置函數。由於某種原因,即使使用空的eval字符串,它也會拋出異常。 –

3

恐怕你的做法有缺陷! 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/