Invoking the Script in WP7 Browser Application

Posted: December 28, 2010 in Development, Windows Phone 7

While writing application that host the WebBrowser control, you’ll need to support refresh, back and forward for the web page shown in the WebBrowser control. While looking at the API for the WebBrowser control you’ll noticed quickly that it wasn’t suppored on the control.  But you can use the InvokeScript call to tell the page to perform these actions:

private void refreshButton_Click(object sender, EventArgs e)
{
  browser.InvokeScript("eval", "history.go()");
}

But when you ran this code, you will get obscure errors (actually, probably COM exception codes, e.g. 80004001). I couldn’t figure out what was going on but then I found the solution:

<phone:WebBrowser x:Name="browser"
                  IsScriptEnabled="True" />

Without enabling scripting, invoking script doesn’t work. Its obvious but hard to discover since the error messages are obscure.  Because the operations may fail if the page has handled certain types of scripts or has a function called eval, you should trap errors in the application.  Here’s what my final Back, Refresh and Forward button functionality look like:

private void backButton_Click(object sender, EventArgs e)
{
  try
  {
    browser.InvokeScript("eval", "history.go(-1)");
  }
  catch
  {
    // Eat error
  }
}

private void refreshButton_Click(object sender, EventArgs e)
{
  try
  {
    browser.InvokeScript("eval", "history.go()");
  }
  catch
  {
    // Eat error
  }
}

private void forwardButton_Click(object sender, EventArgs e)
{
  try
  {
    browser.InvokeScript("eval", "history.go(1)");
  }
  catch
  {
    // Eat error
  }
}

I hope this helps you’ve run into this problem!

Reference : http://wildermuth.com/2010/12/24/Navigating_with_the_WebBrowser_Control_on_WP7

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s