How to bring selenium browser to the front?

22,275

Solution 1

This worked for me to bring the browser window to the foreground. I tested using chromedriver on Selenium 3.6.0 on Python 3.

from selenium import webdriver

driver = webdriver.Chrome()

driver.switch_to.window(driver.current_window_handle)

Related answer in Java - https://sqa.stackexchange.com/questions/16428/how-can-i-bring-chrome-browser-to-focus-when-running-a-selenium-test-using-chrom

Solution 2

To answer your original question, you need to use the maximize window method for the browser to regain focus and be placed in foreground. it should be something like this in Python:

browser.maximize_window()

Solution 3

This is a complete hack, but it worked for me using IE, selenium remote driver in Windows 7.

driver.get("about:blank")  
driver.minimize_window()  
driver.maximize_window()  
driver.minimize_window()  
driver.maximize_window()  

I send a blank page, then minimize and maximize twice. It seems to result in the newly created IE having foreground focus.

Solution 4

Now I don't do python, but how I got around this in Groovy was the following:

browser.js."alert()"
webdriver.switchTo().alert().accept()

I called the javascript alert function which brought the window to the foreground then I dismissed the alert with webdriver.switchTo().alert().accept(). Hopefully there is something similar in Python.

Hope this helps!

Solution 5

In C#, using

Driver.SwitchTo().Window ( Driver.CurrentWindowHandle );

Didn't brung the window to front, but only focused it among other windows, letting it at its Z order.

What worked is the following code :

protected void BringWindowToFront()
{
    var window = Driver.Manage ().Window;
    var position = window.Position;
    window.Minimize();
    window.Position = position;
}
Share:
22,275
Shuman
Author by

Shuman

merge keep

Updated on September 20, 2021

Comments

  • Shuman
    Shuman almost 3 years

    if the browser window is in bg, then this line doesn't work.

    from selenium import webdriver
    
    from selenium.webdriver.common.keys import Keys
    from selenium.webdriver.common.by import By
    # available since 2.4.0
    from selenium.webdriver.support.ui import WebDriverWait
    # available since 2.26.0
    from selenium.webdriver.support import expected_conditions as EC
    
    browser = webdriver.Firefox()
    browser.get(someWebPage)
    
    element = WebDriverWait(browser, 10).until(
        EC.element_to_be_clickable((By.XPATH, '//button[contains(., "Watch")]')))
    
    elements = browser.find_elements_by_xpath('//button[contains(., "Watch")]')
    if elements:
        print 'find watch button',elements
        elements[0].click()
    

    it errors out with

      File "myScript.py", line 1469, in getSignedUrl
        EC.element_to_be_clickable((By.XPATH, '//button[contains(., "Watch")]')))
      File "C:\Python27\lib\site-packages\selenium\webdriver\support\wait.py", line 71, in until
        raise TimeoutException(message)
    TimeoutException: Message: ''
    

    but if i leave my browser window in front, it doesn't error out. is it because i should not use EC.element_to_be_clickable ? i tried ignoring the error and continue to click the button i want, but it says it can not find the button if the browser window is in background. so i think what i should do is before it comes to that line, i bring the browser window to foreground ?

    i saw some people discussing switchTo() ? but my browser object doesn't have that method. what can i do to bring the window to front system independently? thanks

    test system

    python 2.7 windows 7 x64

    python 2.6.6 CentOS 6.4

    edit: i tried

    browser.execute_script("window.focus();")
    

    and

    # commented out EC.element_to_be_clickable as suggested by alecxe
    # element = WebDriverWait(browser, 20).until(
    #     EC.element_to_be_clickable((By.XPATH, '//button[contains(., "Watch")]')))
    print 'sleeping 5'
    time.sleep(5)
    elements = browser.find_elements_by_xpath('//button[contains(., "Watch")]')
    
    print 'before clicking'
    
    from selenium.webdriver.common.action_chains import ActionChains
    hover = ActionChains(browser).move_to_element(elements[0])
    hover.perform()
    
    print elements
    elements[0].click()
    

    not working

    edit2: i checked the doc

    class selenium.webdriver.support.expected_conditions.element_to_be_clickable(locator)[source]
    
        An Expectation for checking an element is visible and enabled such that you can click it.
    

    it seems because when the window is in bg or minimized,the element is not "visible", so this condition is never met ? anyway i tried another condition

    class selenium.webdriver.support.expected_conditions.presence_of_element_located(locator)[source]
    
        An expectation for checking that an element is present on the DOM of a page. This does not necessarily mean that the element is visible. locator - used to find the element returns the WebElement once it is located
    

    it seems this one is working. previously i tried completely removing the condition and it doesn't work maybe simply because i didn't "wait" long (sleep 5 sec ) enough.

    edit3: strangely the same code works fine on a computer with selenium 2.39 python 2.6.6 firefox 28 centos 6.4 even with browser window minimized. but same code tried another two machines failed, browser window has to be maximized and button has to be "visible" A. win7 x64 firefox 28 selenium 2.41 python2.7 B. Fedora 20 firefox 28 selenium 2.41 python2.7

  • Shuman
    Shuman about 10 years
    i tried this on windows 7 x64, firefox windows maximized in the background, i still got the error
  • HRVHackers
    HRVHackers about 10 years
    that's very odd. This will always bring it to the foreground for me. I'm assuming your code looked something like this when you tried my suggestion? try: browser.locateElement(x) except: browser.maximize_window() browser.locateElement(x) Also, out of curiosity, what else do you have running and why can't you just give your browser 100% foreground access (e.g. by giving it a dedicated virtual machine)
  • Shuman
    Shuman about 10 years
    the normal user of it has only one screen, and they need to have a normal firefox window for other work. the selenium firefox is not supposed to be used. and majority user is on windows, how to setup a virtual machine ? for` browser.locateElement(x) `, how do i get a reference to the element x first ? by using xpath ? ( but this assumes x is already there, which may not because it's loaded by ajax, but i can wait long enough for it to show)
  • HRVHackers
    HRVHackers about 10 years
    I'm not following what u mean about users having one screen. Ur company shud be dedicating separate machines be it physical or virtual (using Virtualbox), for your testing.
  • HRVHackers
    HRVHackers about 10 years
    You need to write a function that locates the element using a strtaegy of ur choice, e.g. by xpath. This function will ideally check if element is both present and visible. Then you can click on it
  • Shuman
    Shuman about 10 years
    I'm not using selenium for "testing",actually I'm using it for web scraping, the scrape script use selenium to open a web page in a "real" browser and get some info. Then continue doing its stuff without using the selenium browser. Then 2 hours later. It may needs this browser again. This is all done on the end user's machine. During the scraping process the user may also work on other stuff. But as long as selenium browser window is "blocked" by other window (in the background ) or is minimized, all the element.click() doesn't work.
  • Shuman
    Shuman about 10 years
    ( the exception is raised although after I saw the exception I bring the browser forward I can see the button is visible and clickable ) is this because selenium is designed like this? When "testing" browser window has to be in foreground ( in focus ) ?
  • Shuman
    Shuman about 10 years
    strangely , the same code only works for centos 6.4, selenium 2.39, firefox 28. even if firefox is minimized or in the bg, the button clicking still works. see edit3
  • Taylor D. Edmiston
    Taylor D. Edmiston over 6 years
    I attempted this using the Chrome driver on macOS using Selenium via Python but it didn't have any effect on the window.
  • Admin
    Admin over 4 years
    In C#, I managed to make it work by reaching chromeDriver.Manage().Window and calling Minimize() then Maximize() in a raw on it.
  • etayluz
    etayluz about 4 years
    For Python3: driver.switch_to.window(driver.current_window_handle)
  • Taylor D. Edmiston
    Taylor D. Edmiston about 4 years
    @etayluz Thank you — I've updated the answer to match. It looks like the old method was deprecated.
  • Admin
    Admin over 3 years
    Feels hacky, but worked better than any of the other approaches