I have a Python Selenium script which: A) does stuff on the main window, B) launches a second window C) switches to second window D) does stuff on the second window E) closes the second window F) switches back to the first window, to continue doing stuff.
However, on step F), when I try to switch back to the first window, Chrome issues its "Do you want to leave this site? Changes you made may not be saved" popup.
mainWindow = driver.current_window_handle # remember which window handle is "main"
xpathlink = "//a[.='Click to select']"
driver.find_element_by_xpath(xpathlink).click() # here is step B
print(driver.window_handles) # this confirms yes, there are 2 window handles now
driver.switch_to_window(driver.window_handles[1]) # step C, switch to the newer window handle
#snip # step D - this executes as expected
rowButtonPath = 'xpath_to_button_that_closes_second_window'
driver.find_element_by_xpath(rowButtonPath).click() # step E - closes 2nd window
print(driver.window_handles) # this confirms there's just one window handle again -- the same as the one I started with
driver.switch_to_window(mainWindow) # step F - try to switch back to first one
If I omit the step F line, the script curiously hangs, as if the driver somehow just stopped (I would expect it to go forward, hit the next instance of driver.do_stuff()
, and give an error, but it doesn't even do that.)
The Chrome popup isn't a Selenium alert in the usual sense; otherwise I could just switch_to_alert().accept()
.
It seems empirically the workarounds would be: * get back to the first window in a way that doesn't trigger Chrome's behavior * suppress this Chrome feature by monkeying with Chrome's options when the webdriver instance is initiated
...but I don't know how to do either of those.