[Watir]Control the popup windows created using javascript

本文提供多种处理JavaScript创建的确认、输入及警告弹窗的方法,包括使用Watir库进行自动化测试时如何有效应对这些弹窗。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

These are pop ups created using javascript. The ones below come from the watir unit tests.

They would be created using javascript, and an example is shown under each of them.

<input type = button onClick = 'javascript:x = confirm('Do you really want to do this');">

<input type = button onClick = 'javascript:y = prompt('Enter Something Useful');">

<input type = button onClick = 'javascript:z = alert('This is an alert box');">

Solution #1
http://rubyforge.org/pipermail/wtr-general/2005-April/001461.html

Solution #2

# Auto Popup Handler. Posted by brad@longbrothers.net
#
require 'win32ole'  # already included if you use 'require watir'
#
# Function to look for popups
def check_for_popups
    autoit = WIN32OLE.new('AutoItX3.Control')
    #
    # Do forever - assumes popups could occur anywhere/anytime in your application.
    loop do
        # Look for window with given title. Give up after 1 second.
        ret = autoit.WinWait('Popup Window Title', '', 1)
        #
        # If window found, send appropriate keystroke (e.g. {enter}, {Y}, {N}).
        if (ret==1) then autoit.Send('{enter}') end
        #
        # Take a rest to avoid chewing up cycles and give another thread a go.
        # Then resume the loop.
        sleep(3)
    end
end
#
# MAIN APPLICATION CODE
# Setup popup handler
$popup = Thread.new { check_for_popups }  # start popup handler
at_exit { Thread.kill($popup) }           # kill thread on exit of main application
#
# Main application code follows
# ...

Solution #3

# A Better Popup Handler using the latest Watir version. Posted by Mark_cain@rl.gov
#
require 'watir/contrib/enabled_popup'
#
def startClicker( button , waitTime= 9, user_input=nil )
  # get a handle if one exists
  hwnd = $ie.enabled_popup(waitTime)
  if (hwnd)  # yes there is a popup
    w = WinClicker.new
    if ( user_input )
      w.setTextValueForFileNameField( hwnd, "#{user_input}" )
    end
    # I put this in to see the text being input it is not necessary to work
    sleep 3
    # "OK" or whatever the name on the button is
    w.clickWindowsButton_hwnd( hwnd, "#{button}" )
    #
    # this is just cleanup
    w=nil
  end
end
#
# MAIN APPLICATION CODE
#
$ie = Watir::IE.start( "c:/test.htm" )

# This is whatever object that uses the click method.
# You MUST use the click_no_wait method.
$ie.image( :id, '3' ).click_no_wait
#
# 3rd parameter is optional and is used for input and file dialog boxes.
startClicker( "OK ", 7 , "User Input" )
#
# Main application code follows
# ...

Solution #4

require 'Watir'
require 'watir/contrib/enabled_popup'

# Use click_no_wait to launch the popup or your script will hang
browser.button(:id, /someText/).click_no_wait

hwnd = browser.enabled_popup(5)
if (hwnd)  #yeah! a popup
  popup = WinClicker.new
  popup.makeWindowActive(hwnd)
  popup.clickWindowsButton("Windows Internet Explorer", "OK", "30")
end

Solution #5 - Summary - 09 July 2008

I spent some time trying to figure out how to dismiss javascript popups. The information is out there, but it took a while to get it all put together and then to try out the various suggestions until I found one that worked for me. Here's a summary in case it helps someone else.

1.) You need to update the winClicker.rb file in your watir directory(in my case, it was at: c:/ruby/lib/ruby/gems/1.8/gems/watir-1.5.3/watir). Change the dialog title from "Internet Explorer" to "Windows Internet Explorer". I used the regex /Internet Explorer/ so that it will work no matter which version of IE I use.

2.) Require 'watir/contrib/enabled_popup' for your tests.

3.) Define the popupChecker method to watch for a popup and dismiss it (in this case, by clicking the button with the specified text):

def popupChecker(text)
    Timeout::timeout(2)do
        begin
            if ie.enabled_popup
                hwnd = ie.enabled_popup(5)
                w = WinClicker.new
                w.makeWindowActive(hwnd)
                w.clickWindowsButton_hWnd(hwnd,text)
            end
        rescue Timeout::Error
            puts 'No popup existed'
        end
    end
end

4.) Use the click_no_wait method on the link or button that will launch the popup.

ie.button(:text, 'Continue').click_no_wait

5.) Call the popupChecker method in case a popup exists. You may run into timing problems with the Watir actions that follow the popupChecker. To get around this, I added an ie.wait statement after calling the popupChecker method.

popupChecker('OK')
ie.wait

6.) Some popups are launched by selecting an item from a select_list. Since the click_no_wait method is required on the action that launches the popup, you need something like a select_no_wait method for a select list. Charley Baker provided me with this method:

#select_no_wait method for select lists - needed for popups resulting from select lists
module Watir
    class Element
        #select_no_wait - selects a drop-down element spawning a new process.
        #this is needed to close potential pop-ups that select drop-down can trigger.
        def select_no_wait(item)
            assert_enabled
            highlight(:set)
            object = "#{self.class}.new(self, :unique_number,#{self.unique_number})"
            @page_container.eval_in_spawned_process(object + ".select('#{item}')")
            highlight(:clear)
        end
    end
end

7.) Many people has the problem about click "OK/Cancel" or "OK" in the pop up. I think the code below can deal with the problem

require 'watir'
def check_for_popups(title="Window Internet Explorer", button="OK")
    popup=Thread.new {
        autoit=WIN32OLE.new('AutoItX3.Control')
        ret=autoit.WinWait(title,"",60)
        if (ret==1)
            puts "There is popup."
            autoit.WinActivate(title)
            button.downcase!
            if button.eql?("ok") || button.eql?("yes") || button.eql?("continue")
                autoit.Send("{Enter}")
            else
                autoit.Send("{tab}")
                autoit.Send("{Enter}")
            end
        elsif (ret==0)
            puts "No popup, please check your code."
        end
    }
    at_exit { Thread.kill(popup) }
end

$ie.link(:text,//).click_no_wait
check_for_popups("Window Internet Explorer", "OK")
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值