[C# Helper]
Index Books FAQ Contact About Rod
[Essential Algorithms, Second Edition]

[The Modern C# Challenge]

[WPF 3d, Three-Dimensional Graphics with WPF and C#]

[The C# Helper Top 100]

[Interview Puzzles Dissected]

[C# 24-Hour Trainer]

[Beginning Software Engineering]

[C# 5.0 Programmer's Reference]

[MCSD Certification Toolkit (Exam 70-483): Programming in C#]

Title: Make a web browser that only allows certain web sites in C#

example

The WebBrowser control is a full-featured web browser in a control that you can place on your form. You can use its Navigate method to make the browser go to a specific URL. You can also catch its Navigating event and decide whether to allow the browser to visit a URL.

In this example, you can enter a URL in the TextBox and click Go to make the browser try to visit that site. Here's how the program navigates to the site you enter:

// Try to navigate to the entered URL. private void btnGo_Click(object sender, EventArgs e) { webBrowser1.Navigate(txtUrl.Text); }

This code simply calls the WebBrowser's Navigate method.

The program uses the following code to allow the browser to only go to locations in the www.csharphelper.com domain.

// Verify that this is an allowed web site. private void webBrowser1_Navigating(object sender, WebBrowserNavigatingEventArgs e) { if (e.Url.Host != "www.csharphelper.com") { e.Cancel = true; MessageBox.Show("This web site is prohibited", "Prohibited", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); } }

The Navigating event handler examines the URL's host. If the host isn't www.csharphelper.com, the code cancels the navigation and display an error message.

To test the program, you can enter another web site in the TextBox (such as Google or Yahoo) and click Go. You can also click the Twitter icon (on the lower left in the picture above) to try to go to Twitter.com.

Note that Microsoft doesn't seem to be supporting the WebBrowser control very well. For example, it doesn't seem to understand the latest Unicode emojis and when I run it on this site it has trouble running a script. It works, more or less, but itsn't perfect.

Download the example to experiment with it and to see additional details.

© 2009-2022 Rocky Mountain Computer Consulting, Inc. All rights reserved.