How to connect Selenium Webdriver to existing Firefox/Chrome browser session?

Viewed 6376

This might be a repeated question but I could not find any solution. Recently I found a related post Connecting Selenium WebDriver to an existing browser session but people suggested me to ask a new question.

If any one have tried connecting selenium webdriver to existing browser session that was earlier spawned by selenium itself and had success in doing so, please let me know.

I could find couple of suggestions to try on firefox and selenium 2.X version. But those suggestions do not work for selenium 3.X and there are no solutions for chrome browser.

I have tried all suggestions for Selenium 25.3, firefox v 46 and it works. But for Chrome with chrome driver , I am not able to make it work.

Edited:

Here is the code I have tried:

Starting a firefox driver

System.setProperty("webdriver.gecko.driver", System.getProperty("user.dir")+"/StartFirefoxSession_lib/geckodriver.exe");
WebDriver driver = new FirefoxDriver();
driver.get("http://www.google.com");

Copied RemoteWebDriver source code and changed capabilities from private to protected.

protected Capabilities capabilities; 

Created a new class RemoteDriverEx extending the copied RemoteWebDriver class Changed the NEW_SESSION command issued by the original driver to GET_CURRENT_URL

Response response = execute(DriverCommand.GET_CURRENT_URL, Collections.EMPTY_MAP);

Then craeted a JUnit test to verify

But I am struck with exception

org.openqa.selenium.WebDriverException: No command or response codec has been defined. Unable to proceed
Build info: version: 'unknown', revision: 'unknown', time: 'unknown'
System info: host: 'WPANDBW7HYD', ip: '192.168.56.1', os.name: 'Windows 7', os.arch: 'amd64', os.version: '6.1', java.version: '1.8.0_74'
Driver info: driver.version: RemoteWebDriver
    at org.openqa.selenium.remote.HttpCommandExecutor.execute(HttpCommandExecutor.java:154)

Full code shared @ https://drive.google.com/open?id=0Bz2XxuQQc24KdHVqR3BPaXowUnM

1 Answers

It is possible in selenium all you need is a debugger address of the session you want to connect to. If you are wondering what is debugger address its nothing but the localhost address on which your session is running, it looks like localhost:60003. Now it will be different for each and every case. Below is process with c# code.

  1. Get debugger Address of browser you want to connect later using debug mode as shown in snapshot below. debug driver after browser launch to fetch value

enter image description here

  1. Now keep that browser running and to reconnect the same browser use below code.

ChromeOptions option = new ChromeOptions();

option.DebuggerAddress="localhost:60422";// we need to add this chrome option to connect the required session

driver = new ChromeDriver(option);

driver.Navigate().GoToUrl("https://www.google.com/");

Hope this helps!! let me know in comments if any clarification is required.

Related