Change a C# Variable with InvokeScript

前端 未结 2 1569
我寻月下人不归
我寻月下人不归 2021-01-03 16:57

I need to check if a WebBrowser control in my Windows Phone app has a history, and the way that I figured out how to do that is by using browser.InvokeScript(\"eval\",

相关标签:
2条回答
  • 2021-01-03 17:37
    hasHistory = (bool)browser.InvokeScript("eval", "return (history.length > 0);");
    

    The method InvokeScript returns an object that is the object returned by the script you executed.

    The following code is a bit hackish, but seems to work fine for most cases.

            bool hasHistory = false;
            try
            {
                webBrowser1.InvokeScript("eval");
                hasHistory = true;
            }
            catch (SystemException ex)
            {
                hasHistory = false;
            }
    
    0 讨论(0)
  • 2021-01-03 17:54

    I'm afraid your approach is flawed! the history.length value cannot be used to indicate the page you are on. If you navigate forwards then back, the history length will be 2 to allow forward navigation.

    I solve this problem by tracking navigation in C# code:

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

    As described in this blog post:

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

    0 讨论(0)
提交回复
热议问题