javascriptrubyubuntuwatirfirewatir

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.


Solution

  • 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.