简体   繁体   中英

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

谷歌浏览器提醒

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM