Invoking Javascript Functions from an Instance of Internet Explorer

M

Matthew Lock

Hello,
I am automating Internet Explorer in order to do some simple automated
testing of a web application. How do I invoke Javascript functions in
the web page I load?

I can successfully start an instance of Internet Explorer and control
the DOM, but I don't know how to call Javascript functions. Here is
the code I am using so far:

public class WebBrowser
{
public SHDocVw.InternetExplorerClass ie;

public WebBrowser( string url )
{
ie = new SHDocVw.InternetExplorerClass();
ie.Visible = true;

Object Flags = null, TargetFrameName = null, PostData = null,
Headers = null;
ie.Navigate( url, ref Flags, ref TargetFrameName, ref PostData, ref
Headers );

while( ie.Busy )
{
Thread.Sleep( 500 );
}

mshtml.HTMLDocumentClass document =
((mshtml.HTMLDocumentClass)ie.Document);

// here is where I would like to invoke a javascript function in my
document

ie.Quit();

}
}
 
N

Nicholas Paldino [.NET/C# MVP]

Matthew,

This is pretty easy. Cast your document class to the IHTMLDocument
interface. Then get the object returned from the Script property. Finally,
use reflection to make a call to the underlying javascript method, like so:

// Get the document
mshtml.IHTMLDocument document = ((mshtml.IHTMLDocument) ie.Document);

// Get the script object.
object script = document.Script;

// Make the call:
script.GetType().InvokeMember("my function", BindingFlags.InvokeMethod,
null, script, null);

// Release the script object, and possibly the document object.
Marshal.ReleaseComObject(script);

If you have to pass parameters to the method, you would create an array
which represent the parameters and then pass that into the call to
InvokeMember.
 
M

Matthew Lock

Matthew,

This is pretty easy. Cast your document class to the IHTMLDocument
interface. Then get the object returned from the Script property. Finally,
use reflection to make a call to the underlying javascript method, like so:

Excellent. This is exactly what I was after.

I also discovered document.parentWindow.execScript but unlike
InvokeMethod it doesn't seem to make the return value available.

Thanks,
Matthew
 
M

Matthew Lock

If you have to passparametersto the method, you would create an array
which represent theparametersand then pass that into the call to
InvokeMember.

How would I pass a Javascript object (using this notation
{person:"John", age:"30"} ) as a parameter? I can only seem to pass
string parameters.

Regards,
Matthew Lock
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top