How can I prevent a user from browsing to certain

2019-03-31 05:39发布

问题:

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).

回答1:

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



回答2:

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



回答3:

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