Share via


Windows Phone 7 WebBrowser control and target=”_blank”

I recently ran into a problem where I was hosting some content in a WebBrowser in a Windows Phone 7 app and found that some of the links on the page didn’t work. After a bit of debugging and binging, I found that it was because the links had target=”_blank”. In a regular web browser, this opens up the page in a new tab/window. In the WebBrowser control, it silently does nothing – there are no events you can hook into or anything.

I wanted to share the workaround I used. It’s pretty ugly, but the basic idea is that after the page loads, it injects some JavaScript to go remove the target on any links with target=”_blank”. For this to work, you need to have IsScriptEnabled=true on the control. And, it’s possible that some pages might block eval or otherwise block this from working. But, it worked in my case.

First, you need to hook up the LoadCompleted event on the web browser control. This fires after a page loads:

         public MyPagel()
        {
            InitializeComponent();

            _webBrowser.LoadCompleted += OnWebBrowserLoadCompleted;
        }

Then, OnWebBrowserLoadCompleted injects JavaScript to fix up the links:

         private void OnWebBrowserLoadCompleted(object sender, NavigationEventArgs e)
        {
            try
            {
                _webBrowser.InvokeScript("eval",
@"
window.FixupAnchors=function()
{
    var elems=document.getElementsByTagName('a');
    for (var i=0;i<elems.length;i++)
    {
        if (elems[i].getAttribute('target')!=null && elems[i].getAttribute('target').indexOf('_blank')==0)
        {
            elems[i].removeAttribute('target');
        }
    }
}");
                _webBrowser.InvokeScript("FixupAnchors");
            }
            catch
            {
                // ignore exceptions.
            }
        }

It’s a bit ugly, and some of my coworkers will give me a hard time for swallowing all exceptions here. But, it is working for me and hopefully someone will find it useful.