问题
I'm looking for a way to reattach an existing webdriver browser session to a driver instance so i could control the browser again.
So far, I've tried the following:
I. ==========================================
Reference: https://stackoverflow.com/a/38827934/2285470
Browser: Firefox v. 51.01 / Chrome v. 56.0.2924.87
Driver: geckodriver v. 0.14 / chromedriver v. 2.27
Solution tried:
1. Create a custom class that extends RemoteWebDriver
public class RemoteDriver extends RemoteWebDriver {
public RemoteDriver(URL url, String sessionId) {
super();
setSessionId(sessionId);
setCommandExecutor(new HttpCommandExecutor(url) {
@Override
public Response execute(Command command) throws IOException {
if (command.getName() != "newSession") {
return super.execute(command);
}
return super.execute(new Command(getSessionId(), "getCapabilities"));
}
});
startSession(new DesiredCapabilities());
}
}
- Start a new firefox instance
- Get the session Id and store it somewhere (property file)
- Stop the test, leave the browser open
Invoke the custom class that extends the RemoteWebDriver using the following:
RemoteDriver cdriver = new RemoteDriver(new URL("http://localhost:7055/hub"),"my-session-id");
Result: org.openqa.selenium.WebDriverException: No command or response codec has been defined. Unable to proceed
on the line return super.execute(new Command(getSessionId(), "getCapabilities"));
II. ==========================================
Reference: https://groups.google.com/forum/#!topic/selenium-developers/1LygDvlQ3H4
Browser: Firefox v. 51.01 / Chrome v. 56.0.2924.87
Driver: geckodriver v. 0.14 / chromedriver v. 2.27
Solution tried:
1. Create a custom class that extends RemoteWebDriver
public class RemoteDriver extends RemoteWebDriver {
@Override
protected void startSession(Capabilities desiredCapabilities) {
String sid = getSessionIdFromPropertyFile();
if (sid != null) {
setSessionId(sid);
try {
super.startSession(desiredCapabilities);
} catch (WebDriverException e) {
// session is not valid
sid = null;
}
}
if (sid == null) {
super.startSession(desiredCapabilities);
saveSessionIdToPropertyFile(getSessionId().toString());
}
}
}
- Start a new firefox instance
- Get the session Id and store it somewhere (property file)
- Stop the test, leave the browser open
Invoke the custom class that extends the RemoteWebDriver using the following:
RemoteDriver cdriver = new RemoteDriver();
cdriver.startSession(DesiredCapabilities.firefox());
cdriver.get("https://www.google.com");
Result: org.openqa.selenium.remote.UnreachableBrowserException: Could not start a new session. Possible causes are invalid address of the remote server or browser start-up failure.
Seems others can get it to work but after a few hours of trying I still unable to do this.
I'm using selenium-java version 3.1.0
Thanks in advance.
来源:https://stackoverflow.com/questions/42701350/webdriver-java-reattach-existing-webdriver-browser-session-to-a-driver-instance