3

I have a simple web browser embedded in an application that allows a user to search Wikipedia, and I'm trying to prevent the user from browsing to other websites outside wikipedia (e.g. by clicking an external link the references). Right now, I'm using this simple code:

this.textBoxAddress.Text = this.webBrowser.Url.ToString();
if (this.webBrowser.Url.Host != "en.wikipedia.org")
{
    this.webBrowser.Visible = false;
    this.labelErrorMessage.Visible = true;
}
else
{
    this.webBrowser.Visible = true;
    this.labelErrorMessage.Visible = false;
}

This code works, except the page is already loaded when it's run. If I put this code into the _Navigating event to try to preemptively stop the user before the page is loaded, it fails because the web browser control doesn't update the Url property until after the page is loaded.

The reason I don't like this code is because the page has already loaded when it's called, so any errors in that page (e.g. script errors, which display a popup) show, even though the web page does not.

I've read sources that say not to use the WebBrowser control, for various reasons, but in this case, security isn't a major issue. I also don't need to worry about the end-user doing something, since this application is an in-house application that has literally only one user, and he won't bypass the security.

Disabling all other pages in IE's settings is not a solution either, because this user utilises IE for other surfing, and the intranet sites of this organisation run on IE as well (and those addresses change, so simply allowing all of them would be difficult to anticipate).

Ricardo Altamirano
  • 14,650
  • 21
  • 72
  • 105

3 Answers3

10

Subscribe to the WebBrowser.Navigating event. Check the WebBrowserNavigatingEventArgs.Url property and set WebBrowserNavigatingEventArgs.Cancel=true if it's not wikipedia.

MNGwinn
  • 2,394
  • 17
  • 18
0

Hope this might help http://msdn.microsoft.com/en-us/library/system.windows.navigation.navigatingcanceleventargs

HatSoft
  • 11,077
  • 3
  • 28
  • 43
-1

I think this might be of use to you. Uses the WebBrowser.Document property to find the links and loop through the links and disable the navigation on the links you want. http://programsolution.blogspot.com/2008/01/how-disable-link-navigation-in.html

Brian Hanf
  • 544
  • 2
  • 11
  • 31
  • For your first link, I simply must direct you to [the most voted question on SO](http://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags/1732454#1732454). Parsing HTML with Regex is a terrible idea, plain and simple. – Ricardo Altamirano Jun 21 '12 at 13:55
  • 1
    Believe me, it's not just for my pleasure that no one should ever recommend parsing HTML with regex. It's for the greater good. – Ricardo Altamirano Jun 21 '12 at 14:20