How to Run JavaScript From Watir Scripts

What’s Watir? Read “Watir: Another sweetspot for Enterprise Ruby

Is it possible to run JavaScript functions or execute code from within your Watir test scripts? As a matter of fact it is, but I had a hard time finding the proper documentation for it. Here is what to do and how:

Call JavaScript Functions from Watir script

[code lang=”ruby”]

win = ie.document.parentWindow
win.ToggleProj(‘1’)

[/code]

Inject JavaScript to run from Watir script

I used this to alter a JavaScript function on the existing page:
[code lang=”ruby”]
@ie.document.parentWindow.eval(‘
window.CheckReport=function(){return true}’)
[/code]
As you can see, you can reference the window object and use eval to execute your snippets. The easier way is to add this custom method for easy reference

[code lang=”ruby”]
# Add accessor for DOM window object
class Watir::IE; def window; document.parentWindow; end; end
[/code]
Then you can write the last example as:
[code lang=”ruby”]
@ie.window.eval(‘
window.CheckReport=function(){return true}’)
[/code]
Much more intuitive and straightforward. Thanks to my colleague Tobias for the trick.

More info

Technorati Tags: , , , , ,

One Response to “How to Run JavaScript From Watir Scripts”

  1. Fabienphilipp Says:

    Dear Sir,

    I used a call javascript function from Watir script so as to go to the superior page.
    win = $ie.frame(“home”).document.parentWindow
    win.gotoSeq(‘next’)
    However $ie rest on the old page. Must update on $ie through hwnd for example?

    Yours faithfully,

    Fabien.