My Blog List

Friday, March 16, 2012

Run JavaScript from QTP

Yeah, You can run your pure JavaScript from QTP using RunScript method. Lot of times, we are in need of firing events or simulating actions on web page which is not supported by QTP. At that time, you can use your direct DOM methods and directly execute your script on the web page from QTP like,
  1. Dim MyPage, SearchBox
  2. Set MyPage = Browser("title:=Google").Page("title:=Google")  
  3. Set SearchBox = MyPage.RunScript("document.getElementsByName('q')(0);")
  4. SearchBox.Value="testing"

    'if objects available in frames,
    Set SearchBox = MyPage.RunScript("document.frames(4).document.getElementsByName('q')(0);")

    Set objFrame Browser("title:=Google").Page("title:=Google").Frame("title:=something")
Also, you can execute by obtaining actual browser window object if you have IE app like,
  1. Dim IEApp
  2. Set IEApp = CreateObject("InternetExplorer.Application")
  3. IEApp.document.parentWindow.execScript("document.getElementsByName('q')(0);")
In the same way, you have functions to execute a .js file itself. Here they are
  1. 'For browser object
  2. Browser().EmbedScript
  3. Browser().EmbedScriptFromFile
  4. 'For Page and frame objects
  5. Page().RunScript  / Frame().RunScript
  6. Page().RunScriptFromFile  / Frame().RunScriptFromFile


  1. If jquery is loaded, could you use jQuery's powerful selection engine to grab html elements?

  2. Hi , can you please tell me how to execute the following javascript line in browser using QTP ?

  3. Thanks for sharing great information in your blog. Got to learn new things from your Blog . It was very nice blog to learn about Selenium