Thanks for visiting my blog!
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!