在web自動化測試中點擊一個鏈接然后彈出新窗口是比較司空見慣的事情。
webdriver中處理彈出窗口跟處理frame差不多,以下面的html代碼為例
	window.html
	<html>
	<head><title>Popup Window</title></head>
	<body>
	<a id = "soso" href = http://www.soso.com/ target = "_blank">click me</a>
	</body>
	</html>
下面的代碼演示了如何去捕獲彈出窗口
	require 'rubygems'
	require 'pp'
	require 'selenium-webdriver'
	dr = Selenium::WebDriver.for :firefox
	frame_file = 'file:///'.concat File.expand_path(File.join(File.dirname(__FILE__), 'window.html'))
	dr.navigate.to frame_file
	dr.find_element(:id =>'soso').click
	# 所有的window handles
	hs = dr.window_handles
	# 當前的window handle
	ch = dr.window_handle
	pp hs
	pp ch
	hs.each do |h|
	unless h == ch
	dr.switch_to.window(h)
	p dr.find_element(:id => 's_input')
	end
	end
捕獲或者說定位彈出窗口的關鍵在于獲得彈出窗口的handle。
在上面的代碼里,使用了windowhandles方法獲取所有彈出的瀏覽器窗口的句柄,然后使用windowhandle方法來獲取當前瀏覽器窗口的句柄,將這兩個值的差值是新彈出窗口的句柄。
在獲取新彈出窗口的句柄后,使用switchto.window(newwindow_handle)方法,將新窗口的句柄作為參數(shù)傳入既可捕獲到新窗口了。
如果想回到以前的窗口定位元素,那么再調(diào)用1次switch_to.window方法,傳入之前窗口的句柄既可達到目的。