How to connect Selenium to an existing browser that was opened manually?

Sometimes we come across scenarios where we want Selenium to connect to and use an existing browser that was previously opened manually or by some other program.

Why do we want Selenium to connect to a previously opened browser?

  • Maybe you want to perform some tasks that require manual intervention before kicking in automation execution. For instance, we may need to manually launch the browser, navigate to the desired page, perform some manual tasks like entering captcha manually and then run the automation script to continue from there.
  • Clicking a button on a desktop application opens a webpage. We have some other tool for automating the desktop application but we want Selenium to take control the moment the webpage is opened.
  • Debugging – Let us say we are working on a test script for a certain screen (product checkout) in the application. But the script to reach to that page (add to cart) is not ready yet. We can manually launch the browser and navigate to that page and then run the automation script.

Now, we are back to the original question – How to connect Selenium to an existing browser session?

We can take advantage of the Chrome DevTools Protocol. It allows clients to inspect and debug the Chrome browser.

Prerequisite: Add Chrome to PATH

Please make sure the path to chrome’s executable is added to the environment variable PATH. You can check it by running the command chrome.exe (on Windows) or Google/ Chrome ( on Mac). It should launch the Chrome browser.

If you get a similar message as below that means Chrome is not added to your system’s path:

'chrome' is not recognized as an internal or external command,
operable program or batch file.

If this is the case, please feel free to Google how to add chrome to PATH? If you are on Mac, please follow the steps in This Link.

Step 1: Launch browser with custom flags

To enable Chrome to open a port for remote debugging, we need to launch it with a custom flag –

chrome.exe --remote-debugging-port=9222 --user-data-dir="C:\selenum\ChromeProfile"

For Mac:

Google\ Chrome --remote-debugging-port=9222 --user-data-dir="~/ChromeProfile"

For --remote-debugging-port value you can specify any port that is open.

For --user-data-dir flag you need to pass a directory where a new Chrome profile will be created. It is there just to make sure chrome launches in a separate profile and doesn’t pollute your default profile.

Once Chrome is launched this way it has opened a connection on the given port that any client can connect to for debugging.

You can now play with the browser manually, navigate to as many pages, perform actions and once you need your automation code to take charge, you may run your automation script. You just need to modify your Selenium script to make Selenium connect to that opened browser.

You can verify if the Chrome is launched in the right way:

  • Launch a new browser window normally (without any flag), and navigate to http://127.0.0.1:9222
  • Confirm if you see the Google homepage reference in the second browser window

Step 2: Launch browser with options

Here is that simple but magical Java and Python code. You can easily convert it into a Programming language of your choice.

// JAVA Example
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;

//Change chrome driver path accordingly
System.setProperty("webdriver.chrome.driver", "C:\\selenium\\chromedriver.exe");
ChromeOptions options = new ChromeOptions();
options.setExperimentalOption("debuggerAddress", "127.0.0.1:9222");
WebDriver driver = new ChromeDriver(options);
System.out.println(driver.getTitle());
# PYTHON Example
from selenium import webdriver
from selenium.webdriver.chrome.options import Options

chrome_options = Options()
chrome_options.add_experimental_option("debuggerAddress", "127.0.0.1:9222")
#Change chrome driver path accordingly
chrome_driver = "C:\chromedriver.exe"
driver = webdriver.Chrome(chrome_driver, chrome_options=chrome_options)
print driver.title


What is that value under debuggerAddress?

The URL 127.0.0.1 denotes your localhost. We have supplied the same port, i.e 9222, that we used to launch Chrome with --remote-debugging-port flag. While you can use any port, you need to make sure it is open and available to use.

Troubleshooting

I cannot connect to the browser window.

  • Confirm, if you have launched the browser the same way as described in the tutorial – Check this section
  • Manually go to www.google.com in the same browser window
  • Launch a new browser window normally (without any flag), and navigate to http://127.0.0.1:9222
  • Confirm if you see the Google homepage reference in the second browser window

I can connect to the browser window manually but not through the code.

  • Verify you have imported the right packages. Refer the code block above.
  • Check if you have right chrome driver as per your installed Chrome version. Please refer This Link

If you have found this tutorial useful, please share it with the world.

57 thoughts on “How to connect Selenium to an existing browser that was opened manually?”

  1. Java Code:
    ChromeOptions options = new ChromeOptions();
    options.setExperimentalOption(“debuggerAddress”, “127.0.0.1:9222”);
    System.setProperty(“webdriver.chrome.driver”, “.\\chromedriver.exe”);
    ChromeDriver driver = new ChromeDriver(options);
    driver.findElement(By.name(“q”)).sendKeys(“Saurabh”);

    Reply
  2. Hi,

    When I am trying this in java it is just printing title of current page and after that not performing any actions, please confirm is this issue with java binding ??

    selenium version used 3.12,3.14 and chrome browser version is 68 and chromedriver version is 2.41

    Steps:-
    1. Started chrome
    C:\Program Files (x86)\Google\Chrome\Application>chrome.exe –remote-debugging-port=9222 –user-data-dir=”C:\autoprofile”

    2. Verified Chrome opened in debug mode
    3. Opened seleniumhq website manually and verified debug mode is working
    4. Executed below java code

    import org.openqa.selenium.By;
    import org.openqa.selenium.WebDriver;
    import org.openqa.selenium.chrome.ChromeDriver;
    import org.openqa.selenium.chrome.ChromeOptions;

    public class ChromeDebugger {
    public static void main(String[] args) throws InterruptedException {
    ChromeOptions cp = new ChromeOptions();
    // cp.setExperimentalOption(“–remote-debugging-address”, “127.0.0.1”);
    cp.setExperimentalOption(“debuggerAddress”, “127.0.0.1:9222”);
    System.setProperty(“webdriver.chrome.driver”,
    “./src/test/resources/drivers/chromedriver.exe”);
    WebDriver driver = new ChromeDriver(cp);
    System.out.println(driver.getTitle());
    driver.findElement(By.linkText(“About”)).click();
    System.out.println(driver.getTitle());
    }
    }

    Reply
  3. Hi Experts,

    I am trying to run test cases using selenium on AIX platform. installed Linux version of gecko driver as there is no specific version for aix is available and i am using Mozilla as web browser installed. but gecko driver is not executable on AIX. i have tried many things but not successful any idea for this scenario ?

    Reply
  4. Than you – this is working in Chrome! Do you have the same process to do this in Firefox? I cannot get any Firefox to stay connected.

    Reply
  5. @Saurabh Gupta, this is a great Idea! But when I try to run in python, and try to connect with the code below, instead of connecting to the debugger address it opens another browser..

    chrome_options.add_experimental_option(“debuggerAddress”, “127.0.0.1:9222”)

    Any idea?

    Reply
      • Yes, I opened the chrome from command prompt using the command you suggested. I can open another chrome browser and enter 127.0.0.1:9222 and see any change that’s happening on the first browser, so that part is running fine. But when I run the python code, it opens a new chrome browser with this webdriver code line:
        webdriver.Chrome(chrome_driver, chrome_options=chrome_options)

        Reply
        • I opened the chrome with the following command in the command prompt:
          chrome.exe –remote-debugging-port=9222 –user-data-dir=”C:\Chrome_test”

          Here is my python code:

          from selenium import webdriver
          from selenium.webdriver.chrome.options import Options

          chrome_options = Options()
          chrome_options.add_experimental_option(“debuggerAddress”, “127.0.0.1:9222”)

          chrome_driver = “C:/ChromeDriver/chromedriver.exe”
          driver = webdriver.Chrome(chrome_driver, chrome_options=chrome_options)
          print(driver.title)
          driver.execute_script(“window.scrollTo(0, 800)”)

          Once it executes – driver = webdriver.Chrome(chrome_driver, chrome_options=chrome_options)

          It opens another chrome browser, and a command prompt window. The command prompt window says:
          DevTools listening on ws://127.0.0.1:51608/devtools/browser/c4849860-a50f-4639-8983-b2fd4457db95

          Then when I try to open a webpage through python it opens on the new browser.

          Reply
        • Just wanted to be sure if you are not missing `chrome_options.add_experimental_option(“debuggerAddress”, “127.0.0.1:9222”)`?
          Maybe I can see your full code if it is Ok with you?

          Reply
          • Sure.

            I opened a chrome using the following command:

            chrome.exe –remote-debugging-port=9222 –user-data-dir=”C:\Chrome_test”

            My python code:
            from selenium import webdriver
            from selenium.webdriver.chrome.options import Options

            chrome_options = Options()
            chrome_options.add_experimental_option(“debuggerAddress”, “127.0.0.1:9222”)

            chrome_driver = “C:/ChromeDriver/chromedriver.exe”
            driver = webdriver.Chrome(chrome_driver, chrome_options=chrome_options)
            print(driver.title)

  6. Hi, i folllow your guide, but when I create
    WebDriver driver = new ChromeDriver(options);
    another chrome window open.

    about troubleshooting:

    Confirm, if you have launched the browser the same way as described in the tutorial – Check this section **YES**
    Manually go to http://www.google.com in the same browser window **YES**
    Launch a new browser window normally (without any flag), and navigate to http://127.0.0.1:9222 **YES**
    Confirm if you see the Google homepage reference in the second browser window **YES**

    Reply
  7. Hello,
    Thank you for the article. Could everyone confirm which versions of Selenium , ChromeDriver and chrome browser are applied for a working solution? I’m using the lastest chrome browser (V77), ChromeDriver 2.41 and Selenium 3.4, and it wasn’t working, the new browser is always opened instead of connecting with the existing broswer.

    Reply
    • You would need to use –connect-existing and –marionette-port flags for firefox. I am sorry right now I do not have time to post the full code. I hope I’ll post it soon.

      Reply
    • Hi Krishna, one way would be to implement your learnings in this website to automate user interactions with the gmail. Launch gmail in a browser, enter username/password and login. Search for email by subject and verify.
      However, it is not the recommended way to verify email. The fastest, robust and secure way is to establish a SMTP/IMAP connection using Python/Gmail API and verify email.
      This link may help you in this – https://developers.google.com/gmail/api/quickstart/python

      Reply
  8. Can you run Chrome in Headless mode after configuring this setup.
    Tried:
    chrome_options.headless = True

    This doesn’t work. Can’t use selenium(Python) after closing the window manually after it loads.

    Reply
  9. selenium.common.exceptions.WebDriverException: Message: unknown error: cannot connect to chrome at 127.0.0.1:9222
    from chrome not reachable

    any ideas what this error means? I can’t connect manually to http://127.0.0.1:9222 I get site cannot be reached…..

    Reply
  10. Can you please explain this point
    .Clicking a button on a desktop application opens a webpage. We have some other tool for automating the desktop application but we want Selenium to take control the moment the webpage is opened.

    How can the newly opened chrome with the desktop application, can open it in desired port?

    Reply
    • Hi Nishanth,

      You can make changes in the registry if using Windows, for Mac the option was probably under /Library/? for Google Chrome settings(cant remember for sure). You can specify which port to use to launch Google Chrome. I did it once years back for a similar usecase that you mentioned.

      Reply
    • Hi Nishanth,

      You able get thru the issue? if yes, could you please help me out how i can pass the webdriver control to desktop application which is chrome based pages.

      I could pass the webdriver control to chrome browser which is launched from cmd prompt [chrome.exe –remote-debugging-port=9222 –user-data-dir=”C:\selenum\ChromeProfile” ]

      But i am not able to click or get page title for desktop application.(desktop exe is launched from AutoIt tool, after loading home page i want my selenium code to continue the automation]

      Reply
      • I do not have access to Windows computer at the moment but probably in the below place (in Registry) you can specify the flags remote-debugging-port, –user-data-dir where chrome.exe command is listed –
        HKEY_LOCAL_MACHINE and then SOFTWARE and then Policies and then Google and then Chrome.

        Reply
  11. Hello, great post! Just wondering but does opening a remote debugging port have any security issues if I’m trying to use it on an offline-ethernet machine?

    Reply
  12. Thank you so much for this. Sincerely. I’ve been struggling to get this set up properly for over and hour now until I finally stumbled upon your article. It is greatly appreciated.

    Reply
  13. On hitting “http://127.0.0.1:9222”. I am getting error on chrome that
    “WARNING: This page is deprecated and will be removed by m96. Please use
    chrome://inspect”

    how to work with chrome://inspect

    Reply
  14. hello, is it possible to also connect to a specific tab within an already opened browser? is there a way to reference the tab? also, could you share the code for excel VBA? thank you.

    Reply
  15. Hey , Can we do this using RemoteWebDriver ? Lets say i am running my test through grid on a different machine but i want to use browser opened manually in remote machine . Adding the debuggerAddress is not working as it is not able to get it . Any idea will be helpful .

    Reply
  16. Hi Shadab,
    Thanks for your detailed and error less steps. I was able to achieve it.
    In our framework we are using Webdriver with WebDriver Manager and once I integrate your code above, I am getting below error:
    “SessionNotCreatedException: Could not start a new session. Response code 400. Message: invalid argument: entry 0 of ‘firstMatch’ is invalid”

    Current steps are as follows to get OTP from web outlook:
    Step 1. Enter login details in web app opened through the WebDriverManager (Newly created Browser instance) and wait to get OTP from web Outlook in Step #2 below.
    Step 2. Use the above code by Shadab with 127.0.0.1:9222 setting (already existing browser instance after successful Outlook login)

    Step 2: is failing at WebDriver driver = new ChromeDriver(options); with the above error : SessionNotCreatedException.

    Without the integration, the Step#1 & Step#2 are working fine separately,

    Please can you suggest solution here.

    Reply

Leave a Reply