1

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.

Suzanne
  • 582
  • 2
  • 11
  • 31
  • One idea, you can set opening page which throws popup as a new browser window, then switch to it, do stuff, close it, then again switch to previous (like here http://stackoverflow.com/a/42205370/2397101) – josifoski May 08 '17 at 02:40
  • 1
    But anyway, it should be recognized as alert, with own html structure, in other words if accept() is not working see xpath for clicking Ok – josifoski May 08 '17 at 02:43

1 Answers1

0

As it turns out, omitting step F is the correct answer (and the hanging behavior was an unrelated bug.)

Apparently when the popup closes, it automatically switches back to the first window. Thus, the "switch to first window" command [when it's already there] triggers Chrome to say "Do you want to leave this site?"

Suzanne
  • 582
  • 2
  • 11
  • 31