Sei sulla pagina 1di 7

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></h2></html>");

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 while 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.get
ElementById('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.

Potrebbero piacerti anche