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\",
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:
///
/// 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;
}
}
}
As described in this blog post:
http://www.scottlogic.co.uk/blog/colin/2011/12/a-simple-multi-page-windows-phone-7-phonegap-example/