Navigating with the WebBrowser Control on WP7


Posted by Shawn Wildermuth on Dec 24, 2010 on 4:18AM

GooNews

I am writing a new Windows Phone 7 application called GooNews to show Google News in an application for the phone.  I am writing this application because I needed an app like this. Being able to keep up with news (and create news categories based on keywords) is key to what I wanted to get on my phone. I tried a lot of the other apps out there and when I didn't find what I wanted, I decide to build it myself.

In writing GooNews, I needed to support refresh, back and forward for the web page shown in the WebBrowser control. In looking at the API for the WebBrowser control I noticed quickly that it wasn't suppored on the control.  So a quick search revealed a good solution: 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 I ran this code, I kept getting 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!

 




Application Name WilderBlog Environment Name Production
Application Ver 1.0.0.0 Runtime Framework .NETCoreApp,Version=v1.0
App Path D:\home\site\wwwroot Runtime Version .NET Core 4.0.0.0
Operating System Microsoft Windows 6.2.9200 Runtime Arch X86