Execute Javascript from QuickTest Pro

Despite persistent the rumors to the contrary, you really can execute Javascript from QTP, and not just using Web Extensibility. Here is a simple function that will run some javascript in IE and return the result.

View as plain text
Visual Basic:
Public Function evalJS(oBrowser, sJavaScript)
Set JSEntry = oBrowser.object.document.documentelement.parentnode.parentwindow
On Error Resume Next
evalJS = JSEntry.eval(sJavaScript)
On Error Goto 0
End Function

Set oBrowser = Browser("version:=inter.*")
evalJS oBrowser, "alert('Hello, world');"

*** See the update below ***

That should make IE pop up a "Hello, world" alert. That won't do much for you, but if the page you are testing has a variable set in Javascript, this is a great way to get at it. For instance, an application I work with creates a javascript variable called openPopups that contains the ids of all DivPopups that are currently displayed. To get the first displayed DivPopup, I can run sPopupId = evalJS(oBrowser, "openPopups[0];").

Defining Functions

If you have a Javascript function you want to run, you can define that with evalJS as well. This should get you the same useless output as before and serve the purpose of demonstrating the loading of a javascript function through QTP:

View as plain text
Visual Basic:
sJSFunction = "function alertThis(sThis){ alert(sThis) }"
evalJS oBrowser, sJSFunction
evalJS oBrowser, "alertThis('Hello, world');"
Of course this requires you to squeeze the function into one line. An alternative is to keep your Javascript library in a text file and load it using loadJsLib.

Put this in a text file called c:\jsdemo.js.

View as plain text
JavaScript:
function alertThis (sAlertText) {
alert(sAlertText);
}

function isItOne (iNumber) {
var bReturn = false;
if (iNumber == 1)
{
bReturn = true;
}
return bReturn
}
Now run this in QTP. Make sure evalJS is available too.

View as plain text
Visual Basic:
Function loadJsLib ( oBrowser, sLibPath )
Set fso = CreateObject("Scripting.FileSystemObject")
Set f = fso.OpenTextFile(sLibPath, 1)
sLibText = f.ReadAll
loadJsLib = evalJS( oBrowser, sLibText)
End Function

LoadJsLib oBrowser, "c:\jsdemo.js"
print evalJS(oBrowser, "isItOne(1)")
UPDATE: MJP points out in the comments that evalJS may not work as written for everybody. If you have trouble with it, try changing the first line to:

View as plain text
Visual Basic:
Set JSEntry = oBrowser.Page("micClass:=Page").object.documentelement.parentnode.parentwindow
UPDATE 2: I realized I didn't give credit where credit is due. I got the idea from this article at Ajaxian and applied a few hours of hacking to get it working in vbscript on IE. The ironic part is that it was the code they said would only work on Firefox that gave me the idea to try eval in IE. The window.execScript method they write about for IE was useless to me because I needed a return value.