说说watir-webdriver那些事(七)如何处理JS弹出窗口

首先举个例子,html的js弹出窗口的代码如下:

<html>

    <head><title>Popup Window</title></head>

    <body>

	<input id = "btn" value = "click" type = "button" onclick = "alert('hello');"/>
    </body>

</html>
 当点击按钮会弹出相应的js提示框来,我们一般叫他js弹出窗口。

 

对于JS的弹出窗口一般常见的有两种,alert/confirm两种,watir-webdriver也有自己的处理方式,我先贴出来:

 

 

require "watir-webdriver/extensions/alerts"
JAVASCRIPT ALERTS
browser.alert do
  browser.button(:value => 'Alert').click
end #=> 'the alert message'
JAVASCRIPT CONFIRMS
browser.confirm(true) do
  browser.button(:value => 'Confirm').click
end #=> 'the confirm message'
JAVASCRIPT PROMPT
browser.prompt('hello') do
  browser.button(:value => 'Prompt').click
end #=> { :message => 'foo', :default_value => 'bar' }
 

不过我用起来,不太方便,我觉得调用底层的selenium-webdriver会比较简单,比方说处理alert的方法

 

 

 

a = b.driver.switch_to.alert
p a.text
a.accept

 

如果使用Confirm取消用a.dismiss。这样用起来比较简单

 

还有一种方式就是就是不让窗口弹出来,主要是通过覆盖js原有的方法,具体代码如下,可供参考

 

 

# 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}")

你可能感兴趣的:(webdriver)