Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to handle browser javascript confirm navigation alert with ruby watir script

I'd like to programmatically handle the javascript confirmation alert asking if you'd like to leave the page (See screenshot below).

google chrome alert

The methods that I've tried so far have not worked.

The browser is not recognizing that I am returning the value true for wanting to leave the page.

This is the part where I am trying to handle this alert:

if  @b.div(:class, "infoMessageBox error").present?
        puts "There was an error"
        #@b.execute_script("window.confirm = function() {return true}")
        @b.execute_script("window.onbeforeunload = function() {};")
        @b.goto("#{@env}/TranslateFile.aspx")
        break
    end

I have also read this article: "Dismiss "Confirm Navigation" popup with Watir" but the method in this article does not help in my case.

I would apreciate some help because I'm stuck right here.

THIS HELPED in solving my problem.

I improved the code and now it works better but here might be some other problems in future (hope not).

@b.refresh
if @b.alert.exists?
    @b.alert.text
    @b.alert.ok 
end
@b.goto("#{@env}/TranslateFile.aspx")

This helped me and now it escapes the alert and continues the workflow. Thanks for help ! :)

More info for others who might have trouble with handling the alerts ( link located below ):

# Check if alert is shown
browser.alert.exists?

# Get text of alert
browser.alert.text

# Close alert
browser.alert.ok
browser.alert.close
JAVASCRIPT CONFIRMS
# Accept confirm
browser.alert.ok

# Cancel confirm
browser.alert.close
JAVASCRIPT PROMPT
# Enter text to prompt
browser.alert.set "Prompt answer"

# Accept prompt
browser.alert.ok

# Cancel prompt
browser.alert.close

# don't return anything for alert
browser.execute_script("window.alert = function() {}")

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

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

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

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

# don't return anything for leave page popup
browser.execute_script("window.onbeforeunload = null")

Documentation from watir

like image 299
Edgars Karķis Avatar asked Aug 17 '26 00:08

Edgars Karķis


1 Answers

Answer is: you can try to use alternative method, such as: @b.alert.exists? if it return true, then: @b.alert.close

I think this can help you in future

like image 157
Alex Holubenko Avatar answered Aug 21 '26 01:08

Alex Holubenko