Invoking Javascript From a WebBrowser Control
Invoking Javascript From a WebBrowser Control
Today I got a
request to use
A WebForms application
inside a WinForms
application. One problem
that we needed to solve
was how to make an
interaction between the WinForm and the WebForm it uses.
The post will show the solution.
Invoking Javascript From a WebBrowser Control
When you want to use a WebForm within a WinForms
application you should use the WebBrowser control. Taken from
MSDN the WebBrowser control “Enables the user to navigate Web
pages inside your form.”.
One of the nice features of the WebBrowser control is its ability to
invoke Javascript. On the other hand, WebForm Javascript can also
invoke methods in the WinForms which host them using a the
WebBrowser control.
Lets see how to do so.
The first thing to do is to enable scripting on the WebBrowser control.
This can be achieved by the following code:
webBrowser1.ObjectForScripting = this;
As you can see we use the ObjectForScripting property of the
WebBrowser control and give it the form which it is located in.
This property must be set in the form's constructor or the form’s Load
event. In order to invoke a Javascript which is located inside a WebForm
we need use the Document property of the WebBrowser control and
from the document the InvokeScript method. The InvokeScript
method gets as parameters the method name to invoke and a set
of parameters. For Example:
webBrowser1.Document.InvokeScript("doLogin");
will invoke the doLogin method which is located in the WebForm.
In order to do the opposite, which is to invoke a method that is
located in the WinForm from the WebForm, we use the
window.external method and call from it the method in the WinForm.
For example the following example will call a method called
Say which get a string as its parameter:
window.external.Say('Hello')
The method on the WinForm must be public or else the operation
will fail.
Summary
Since I had a need for two ways communication between a
WinForms application and a WebForms application I used the
WebBrowser control which enables this behavior. I hope this
will help you if you’ll need such a solution in your application.
CodeProject