Monday, February 16, 2009

An ingenious solution for handling Javascript popups in Watir

So I've been struggling to figure out how to elegantly and properly handle popups on Watir. I've read and tried all five solutions listed on http://wiki.openqa.org/display/WTR/JavaScript+Pop+Ups but still couldn't find one that works well for the version of Ruby/Watir I am using.

I'm using Ruby 1.8.6 and Watir 1.6.2, BTW.

Then I came across a blog post that proposes to override the javascript alert and confirm functions. Read the whole thread from google groups here.

I was stoked !!! Even more so that it worked beautifully.

What I did was to encapsulate it into a def which accepts the IE instance created by watir.


def replace_js_popups(ie)
ie.document.parentWindow.execScript("window.confirm=function(){return true}");
ie.document.parentWindow.execScript("window.alert=function(){return true}");
end


Now, right after going to a page, I would call on "replace_js_popups" to override both confirm and alert, like so.


ie = Watir::IE.new
ie.goto(url_with_popup_here)
replace_js_popup


Of course, this is not a fool proof solution. By replacing the alert and confirm functions with a function that always returns true, you will need to always expect the popups to return a value of true in your automated tests.

No comments:

Post a Comment