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.

Author: Alister Scott

Alister is an Excellence Wrangler for Automattic.

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?


      1. Script becomes frozen after click on the link that leads to page with alert onload (when I clicks ‘OK’ manually it runs on as it should). I’ve tried to execute it before click the link but it has no effect. Think I do something wrong but what exactly?


      1. Scott, thank you for quick response. I am using watir.
        Yes, i am trying to execute the Javascript inside the frame.
        My code look like this:
        @browser.frame(:id, @frame_id).execute_script “window.confirm = function() { return true; }”
        @browser.frame(:id, @frame_id).button(:id, “btnDelete”).click

        Similar code works fine on the pages without frames.


Comments are closed.