Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby Watir: Clicking OK on JavaScript Alerts?

Seems none of the code I've tried has any affect. My intention is to close any and all JavaScript prompts that may come up by hitting the "OK" button. Problem is, my script has no affect on the prompts that come up. In other words, it does nothing.

Here's what I have:

fx = FireWatir::Firefox.start(somepage)
fx.startClicker("OK")
fx.button(:id, "OK").click
fx.button(:id, "CONFIRM").click

The HTML:

<script type="text/javascript">
    alert("Alert!");
    window.confirm("Confirm?");
</script>

The text in the prompts can change, my intention is to hit OK regardless of what is inside the alert/confirm prompt.

PS: I'm running Ubuntu.

like image 700
Marco Avatar asked Feb 12 '10 02:02

Marco


2 Answers

The best way is to stop pop-ups from triggering at all.

require 'watir'
b = Watir::Browser.start "http://somepagewithdialogs"
# don't return anything for alert
b.execute_script("window.alert = function() {}")

# return some string for prompt to simulate user entering it
b.execute_script("window.prompt = function() {return 'my name'}")

# return null for prompt to simulate clicking Cancel
b.execute_script("window.prompt = function() {return null}")

# return true for confirm to simulate clicking OK
b.execute_script("window.confirm = function() {return true}")

# return false for confirm to simulate clicking Cancel
b.execute_script("window.confirm = function() {return false}")

# interact with some element which would trigger the pop up
b.button(:id => "dialogTrigger").click

See: http://watirmelon.com/2010/10/31/dismissing-pesky-javascript-dialogs-with-watir/ for more detail.

like image 112
Alister Scott Avatar answered Nov 18 '22 13:11

Alister Scott


this was asked an eternity ago so I'm just adding something a little more updated that did it for me

@browser.alert.exists? @browser.alert.ok @browser.alert.close

first one will return a boolean second one will ok whatever action you are prompted to do and third one will close the alert with no

like image 1
trickymuffin Avatar answered Nov 18 '22 14:11

trickymuffin