views:

279

answers:

2

I had a look here: http://wiki.openqa.org/display/WTR/JavaScript+Pop+Ups

Every solution is for IE on Windows. I am using Firefox on Mac. Is there a way to click on OK of a JavaScript alert box?

+2  A: 

Proper handling of alerts and prompts is still being worked on in WebDriver, but a common workaround is to overwrite the window functions using execute_script(), i.e.

browser.execute_script("window.alert = function(msg) { window.lastAlert = msg; }")
browser.button(:id => "trigger-alert").click
browser.execute_script("return window.lastAlert") #=> "the message"

Since I'd like to avoid a bunch of monkey patches floating around (a common problem in the Watir community), I've added some helper methods as an optional require - after the next release you should be able to do:

require "watir-webdriver/extensions/alerts"

browser.alert do
  browser.button(:id => "alert").click 
end #=> "the alert message"

browser.confirm(true) do
  browser.button(:id => "confirm").click
end #=> "the confirm message"  

browser.prompt("returned value") do
  browser.button(:id => "prompt").click 
end #=> { :message => "foo", :default => "bar" }

Note that this is temporary and the API may be removed in the future when the issue is resolved in WebDriver.

jarib
I had an error using browser.alert and I fixed it with a hack, but you might want to had a look: http://gist.github.com/569969
rtacconi
The current behaviour is correct - if the button doesn't exist, it should raise an error. The idea is that you will write your own code in the block that will trigger the alert.
jarib
Sorry, I was calling it in the wrong place. However I tried your code but does not click any alert: assert_exists': unable to locate element, using {:value=>"OK", :tag_name=>"button"}
rtacconi
The code in the block should contain the action needed to *trigger* the alert. Check out the tests here http://github.com/jarib/watir-webdriver/blob/master/spec/alert_spec.rb and the corresponding HTML here http://github.com/jarib/watir-webdriver/blob/master/spec/html/alerts.html for an example of how it works.
jarib
+1  A: 

I know that the iMacros for Firefox addon can click these alert boxes. Maybe you can combine it with our setup?

SamMeiers