Tuesday, February 2, 2010

Closing Javascript Alerts in Selenium Tests

I have been plagued some time now with a problem in my Selenium testing, the dreaded modal Javascript alert generated from the "onload" event (See the Selenium FAQ for more info). OK, maybe dreaded is a bit strong of a word, but it has been quite frustrating in trying to automate vendor provided code that we cannot change. Finally there is a fix.

Jason Huggins, the creator of Selenium, presented at JSConf 2009 and demonstrated a way around Javascript alerts that Selenium cannot handle. After speaking with Jason, he provided me with the original code snippet from Aaron Boodman and I have created a Firefox extension for general use that can be downloaded from my Github site.

The magic happens in a function called alertClose. If all you need to do is close an alert it should work unmodified for you. If you need to do something a little more exotic you may need to edit the subject.location which specifies what types of windows it closes. By default it points to chrome://global/content/commonDialog.xul, which is the chrome type for alert boxes. There is a Mozillazine article that has a listing of the various types of chrome windows if you need to customize.



So there you have it. A very simple way to get around Javascript alerts. Hopefully this solution is only temporary and the new WebDriver code being integrated into Selenium 2 will work around it in a more elegant way.

No comments:

Post a Comment