Navigating with the WebBrowser Control on WP7


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!

 



Shawn
Shawn Wildermuth
Author, Teacher, and Coach



My Courses

pluralsight
Building a Web App with ASP.NET Core, MVC6, EF Core, Bootstrap and Angular (updated for 2.0)
Using Visual Studio Code for ASP.NET Core Projects (new)
Implementing and Securing an API with ASP.NET Core
Building a Web App with ASP.NET Core, MVC6, EF Core and AngularJS
Building a Web App with ASP.NET5, MVC6, EF7, and AngularJS (Retired)
Best Practices in ASP.NET: Entities, Validation, and View Models
Webstorm Fundamentals
Front-End Web Development Quick Start
Lessons from Real World .NET Code Reviews
Node.js for .NET Developers

Application Name WilderBlog Environment Name Production
Application Ver 2.0.0.0 Runtime Framework .NETCoreApp,Version=v2.0
App Path D:\home\site\wwwroot\ Runtime Version .NET Core 4.6.26020.03
Operating System Microsoft Windows 10.0.14393 Runtime Arch X86