Skip to content

Commit a2c8639

Browse files
committed
[py] Fix W3C switching to window by name.
1 parent dcfab90 commit a2c8639

File tree

2 files changed

+32
-3
lines changed

2 files changed

+32
-3
lines changed

py/selenium/webdriver/remote/switch_to.py

Lines changed: 23 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,7 @@
1818
from .command import Command
1919
from selenium.webdriver.common.alert import Alert
2020
from selenium.webdriver.common.by import By
21-
from selenium.common.exceptions import NoSuchElementException, NoSuchFrameException
21+
from selenium.common.exceptions import NoSuchElementException, NoSuchFrameException, NoSuchWindowException
2222

2323
try:
2424
basestring
@@ -106,7 +106,27 @@ def window(self, window_name):
106106
:Usage:
107107
driver.switch_to.window('main')
108108
"""
109-
data = {'name': window_name}
110109
if self._driver.w3c:
111-
data = {'handle': window_name}
110+
self._w3c_window(window_name)
111+
return
112+
data = {'name': window_name}
112113
self._driver.execute(Command.SWITCH_TO_WINDOW, data)
114+
115+
def _w3c_window(self, window_name):
116+
def send_handle(h):
117+
self._driver.execute(Command.SWITCH_TO_WINDOW, {'handle': h})
118+
119+
try:
120+
# Try using it as a handle first.
121+
send_handle(window_name)
122+
except NoSuchWindowException as e:
123+
# Check every window to try to find the given window name.
124+
original_handle = self._driver.current_window_handle
125+
handles = self._driver.window_handles
126+
for handle in handles:
127+
send_handle(handle)
128+
current_name = self._driver.execute_script('return window.name')
129+
if window_name == current_name:
130+
return
131+
send_handle(original_handle)
132+
raise e

py/test/selenium/webdriver/common/window_switching_tests.py

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -42,6 +42,15 @@ def testShouldSwitchFocusToANewWindowWhenItIsOpenedAndNotStopFutureOperations(dr
4242
assert driver.current_window_handle == handle
4343

4444

45+
def testCanSwitchToWindowByName(driver, pages):
46+
pages.load("xhtmlTest.html")
47+
handles = driver.window_handles
48+
driver.find_element(By.LINK_TEXT, "Open new window").click()
49+
WebDriverWait(driver, 3).until(EC.new_window_is_opened(handles))
50+
driver.switch_to.window("result")
51+
assert driver.title == "We Arrive Here"
52+
53+
4554
def testShouldThrowNoSuchWindowException(driver, pages):
4655
pages.load("xhtmlTest.html")
4756
with pytest.raises(NoSuchWindowException):

0 commit comments

Comments
 (0)