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
win.ToggleProj(’1′)
Inject JavaScript to run from Watir script
I used this to alter a JavaScript function on the existing page:
window.CheckReport=function(){return true}’)
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
class Watir::IE; def window; document.parentWindow; end; end
Then you can write the last example as:
window.CheckReport=function(){return true}’)
Much more intuitive and straightforward. Thanks to my colleague Tobias for the trick.
More info
- Justaddwater.dk: Watir: Another sweetspot for Enterprise Ruby (July 2006)
- Telerik (by Egil): Automating Complex JavaScript-rich Controls with Watir (April 2006)
- DWatir for distributed testing is very promising. I saw the demo at RailsConf but had not yet a chance to use. More info in the code files.
Technorati Tags: ruby, enterprise, business case, watir, testing, javascript

January 2nd, 2008 at 19:41 (GMT-1)
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.