Dismissing pesky JavaScript dialogs with Watir

Dismissing JavaScript dialogs has historically been an issue when using Watir, demonstrated by the lengthy JavaScript Pop Ups wiki page full of complex, messy code with multiple sleep statements and polling to dismiss these pesky things.

Recently a fellow ThoughtWorker showed me a much simpler and more elegant solution, which he had learned off another ThoughtWorker.

It simply overrides the JavaScript function being called and returns true always, so the dialog never appears.

b.execute_script "window.alert = function() { return true; }"

The beauty of this solution is you don’t need to use problematic click_no_wait method like all the other solutions available, and you can override any JavaScript function, including the three types of dialogs.

require 'watir'
b = Watir::Browser.start "http://www.sislands.com/coin70/week1/dialogbox.htm"
b.execute_script "window.confirm = function() { return true; }"
b.execute_script "window.alert = function() { return true; }"
b.execute_script "window.prompt = function() { return true; }"
b.button(:value => 'confirm').click

The downside is it only works in Internet Explorer at the moment; I am trying to work out why it doesn’t work in FireWatir.

I’ll update the wiki page to include this solution so other don’t waste time on complex polling techniques.

Update: 6 Nov 2010

Jarmo Pertman has written an excellent follow up post to this one, where he talks in more detail about what values you should return. You should check it out.

9 thoughts on “Dismissing pesky JavaScript dialogs with Watir

  1. Thank you, this is a very convenient way. It works when I want to dismiss the dialog that appears after clicking on the button or link. But I can’t bypass the alert that appears at once when the page is loaded. How to solve this problem?

Comments are closed.