Search
Sponsor
Winners

Win Prizes

Social Presence
Twitter Twitter LinkedIn YouTube Google

Like us on Facebook
Advertisements
Top Articles Author
Wed, 22-Oct-2014 Authors
All Time Authors
Sourav.Kayal
39750
Sheonarayan
38050
Niladri.Biswas
33350

Latest members | More ...


(Statistics delayed by 5 minutes)
Ads
 Article

Working with WebBrowser in WPF

Abhi2434
Posted by under WPF category on for Beginner level | Views : 142349 red flag
If you found plagiarised (copied) or inappropriate content,
please let us know the original source along with your correct email id (to communicate) for further action.
Rating: 3.9 out of 5
10 vote(s)
This article demonstrates how you can use WebBrowser control to show html document within your WPF application. You will find the basic usage of powerful WebBrowser control that comes with WPF.

You can also find how you can communicate the document from external wpf application and vice versa. A sample application is also provided to demonstrate each of these.

 Download source code for Working with WebBrowser in WPF


Introduction


WPF introduces WebBrowser control to ensure that we can show html pages embedded inside the control. It is really very important to know how to use a WebBrowser as while working with WPF, if you want to show content from the server as HTML, or load an html document directly inside the WPF window, this control will be the only option to you. A WebBrowser control actually uses Internet Explorer Browser Engine internally, so you need it to be installed in the machine (which of course every machine installs by default ) before loading it inside the WPF control. So if you update the IE of your machine, the web browser will update as well.

In this article I will discuss the basic usage of WPF WebBrowser control, so that the use of this would come to you very easy.



Basic Usage

It is very easy to use WebBrowser control in your WPF application. In your XAML you may include

<WebBrowser x:Name="wbMain" Margin="30">
</WebBrowser>

This will create a WebBrowser Control within your WPF window. Now to load a document, either you have to navigate to a site or directly load the document from your application.

Lets for instance,

wbMain.NavigateToString("<HTML><H2><B>This page comes using String</B><P></P></H2>");

Here, NavigateToString will load the string data into the WebBrowser. So basically you need to pass an html body directly to the WebBrowser control using this method as string.

On the other hand, if you like to do the same thing using Stream, you might go for NavigateToStream which takes a Stream as method argument and loads it.

Uri uri = new Uri(@"pack://application:,,,/mypage.htm");
Stream source = Application.GetContentStream(uri).Stream;
wbMain.NavigateToStream(source);

For instance, you can see I have been using the relative url of the package resource which is loaded into the stream and loaded to the browser using NavigateToStream method. You can also go for normal urls to load this rather than using the Content url using this.

Similar to this, you can also load data from a file located in your hard drive. To do this, you might either read the entire file into a string/stream, using the method I have provided earlier, or you can load the entire data in your webbrowser control. You can also use the general method Navigate to navigate your page to any location directly using either unc path or normal web address.

So say I write :

wbMain.Navigate(new Uri("http://www.abhisheksur.com", UriKind.RelativeOrAbsolute));

It will load the my entire website directly within your WebBrowser control inside the WPF window. Similarly you can also use

wbMain.Navigate(new Uri("c:/xyz/TestFile.htm"));

You can see this will load the file into the WebBrowser control.

Regarding other normal methods you might use

if (wbMain.CanGoBack)
{
     wbMain.GoBack();
}

if (wbMain.CanGoForward)
{
      wbMain.GoForward();
}

to back and forth between the pages. It is always better to use CanGoBack and CanGoForward  to check whether the navigation is possible or not before using GoBack or GoForward.

Theme a WebBrowser

Theme a WebBrowser means actually theme the web document. Web document can be themed only using html. You need to know basic html styles to theme a document inside the WebBrowser. For instance you might use CSS to change the color of the ScrollBar that suits your Application.

<style type=\"text/css\"> body { scrollbar-base-color:black; }</style>

This will create a black styled browser window just like shown above with black scrollbars. For further knowledge, you can read on CSS and htmls.

Overcoming Security warning in WebBrowser

This is not the end of this. There are lots of things that you can do using the WPF web browser control. For instance, the most general issue that everybody face while loading an html file with full javascript control is the trust panel. According to the settings that you might have implied to your internet explorer browser, it might not trust a disk html file directly in your web browser.

Say for instance, I have a file which shows a javascript alert when the page is loaded.

<script type="text/javascript">
function getAlert(){
alert("Hi the page is loaded!!!");
}
window.onload = getAlert;
</script>

So you can see, when the window is loaded the page will display an alert message. Now if I load the page using

wbMain.Navigate(new Uri("pack://siteoforigin:,,,/myalertpage.htm", UriKind.RelativeOrAbsolute));

Or any path local to the system, you will end up the security warning like “To help protect your security, your web browser has restricted this file from showing active content that would access your computer…” like as shown in the picture :

This is a general problem to everybody while using WPF WebBrowser. To overcome this, you need to either load the html as content stream or write

<!-- saved from url=(0014)about:internet -->\n\r

as your first line of document. This will instruct that the page is loaded from about:internet and will not display the Security warning. (0014) indicates how much to read as url. As about:internet uses 14 characters, we need to use 14 in braces.

You can also use

<!-- saved from url=(0019)www.abhisheksur.com -->\n\r

if you want to. The url takes 19 letters, so I specified it as 19.

Access Javascript from WPF WebBrowser

Accessing javascript from the webbrowser or invoking a .NET object can be done very easily using WPF WebBrowser control.

Invoke C# method from Javascript

Communication between html document and WPF requires you to have full trust between the applications. In javascript, window.external points to the external application, which you might use to invoke a method outside the WebBrowser.

To do this you need to create an interface between the two. A helper method should be used to which could be accessed directly using Javascript. Let us look how we can achieve this using WPF WebBrowser Control.

[PermissionSet(SecurityAction.Demand, Name = "FullTrust")]
[ComVisible(true)]
public class ObjectForScriptingHelper
{
    Mainwindow mExternalWPF;
    public ObjectForScriptingHelper(Window1 w)
    {
        this.mExternalWPF = w;
    }
    
}

So basically the class allows you to invoke a .NET method directly from javascript. This helper class is set Permission to FullTrust and also ComVisible. So our WebBrowser, which is actually a Com element can directly communicate with the class to invoke method within the class ObjectForScriptingHelper, which is the parent window on which the browser is loaded. The javascript will allow to use window.external to point to this class.

[PermissionSet(SecurityAction.Demand, Name = "FullTrust")]
[ComVisible(true)]
public class ObjectForScriptingHelper
{
    Mainwindow mExternalWPF;
    public ObjectForScriptingHelper(Window1w)
    {
        this.mExternalWPF = w;
    }
    public void InvokeMeFromJavascript(string jsscript)
        {
            this.mExternalWPF.tbMessageFromBrowser.Text = string.Format("Message :{0}", jsscript);
        }
    
}

Say I have a method InvokeMeFromJavascript within the class ObjectForScriptingHelper class. To use this class you need to create an object of it and pass it to the property ObjectForScripting of WebBrowser control.

So I write,

ObjectForScriptingHelper helper = new ObjectForScriptingHelper(this);
this.wbMain.ObjectForScripting = helper;

Now Lets navigate to an html with :

<input type="text" id="txtMessage" />
<input type="button" value="InvokeMe" onclick="javascript:window.external.InvokeMeFromJavascript(document.getElementById('txtMessage').value);" />

This will load a textbox and a button. See in the code above, I have used window.external to call the same function that I have declared in the ObjectForScriptHelper class. Thus when you click on the Button inside the WebBrowser, you will see the message been displayed in the TextBlock outside it.

In the above image, when the user clicks on InvokeMe inside the WebBrowser, it will update the TextBlock placed outside.

Invoke Javascript method from C#

Now it is time to do the reverse. Lets suppose you want to invoke a javascript method from C#. This is also can easily be done using InvokeScript method. The InvokeScript method of WebBrowser control allows you to pass data from the external WPF application to the document loaded in the WebBrowser.

Let us take a look at how you can do this.

function WriteFromExternal(message){
	document.write("Message : " + message);
}

Inside the html document, I wrote a simple javascript method named WriteFromExternal which takes a string argument. Now to invoke this method, you need to use

this.wbMain.InvokeScript("WriteFromExternal", new object[] { this.txtMessageFromWPF.Text });

Therefore the text written in the TextBox outside the WPF WebBrowser control gets passed to the javascript and hence the document gets refreshed with the Message.

You can see I have clicked the Button CallDocument which invokes the javascript method inside the Document with the message “Pass to JS” and which in turn writes the entire string within the document.

Conclusion

So it is very easy for a programmer to work with WPF WebBrowser control as it is very flexible according to our requirement. I hope you like this article very much. Any feedback is welcome. Thank you.

Page copy protected against web site content infringement by Copyscape
About the Author

Abhi2434

Full Name: Abhishek Sur
Member Level: Silver
Member Status: Member,Microsoft_MVP,MVP
Member Since: 12/2/2009 4:19:08 AM
Country: India
www.abhisheksur.com
http://www.abhisheksur.com

Working for last 2 and 1/2 years in .NET environment with profound knowledge on basics of most of the topics on it.
Login to vote for this post.
Found interesting? Add this to:


Comments or Responses

Posted by: Raja on: 4/8/2010

Very creative and informative article as always Abhishek, keep it up!



Posted by: Abhi2434 on: 4/8/2010

Thank you so much Raja for your comment.

I am glad that you like this article.

Posted by: Apelbaum on: 1/19/2011 | Points: 25

Thank you Abhishek for the post. Do you know if you can also change the Zoom as that is standard in the IE but do not seem to able to control this from WPF. Ideally I would to have a user control (scroll) that can zoom in and out.

Thanks Eidan

Posted by: Sundeepyama on: 1/4/2012 | Points: 25

Quick start guide for web browser control

Posted by: Hate_Indus on: 3/24/2012 | Points: 25

Code you posted in this article does not working!!!!!!!!!!!! WTF?
Uri uri = new Uri(@"pack://application:,,,/mypage.htm");
Stream source = Application.GetContentStream(uri).Stream;
wbMain.NavigateToStream(source); WTF?
I HATE FUCKING INDIAN DEVELOPERS.

Posted by: Pattormey on: 5/31/2012 | Points: 25

"I HATE FUCKING INDIAN DEVELOPERS. "
This comment from Hate_Indus is uncalled for and an embarrassment to the rest of us..

There is only this one world and we share it.. unfortunately we also share it with morons like Hate_Indus.

Thanks for your contribution

Pat Tormey NH USA


Posted by: Ericouellet on: 6/11/2014 | Points: 25

Thanks a lot,

Very nice sample. I created an account just because I thought your sample really worth it :-) !!!

Sorry for Hate_Indus... There will always be stupid people on earth that has time to waste...

Continue to give us great sample... We really appreciate them!

Login to post response

Comment using Facebook(Author doesn't get notification)