To run Selenium in an already open browser window in Java, you can use the `RemoteWebDriver` class and the `attachToSession` method. Here's an example code that shows how to attach to an already open Chrome window:
```java
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.remote.RemoteWebDriver;
import java.net.URL;
public class AttachToChromeWindow {
public static void main(String[] args) throws Exception {
// get the session ID of the open Chrome window
String chromeSessionId = "1234567890"; // replace with the actual session ID
// attach to the session using RemoteWebDriver
ChromeOptions chromeOptions = new ChromeOptions();
chromeOptions.addArguments("--start-maximized");
DesiredCapabilities capabilities = DesiredCapabilities.chrome();
capabilities.setCapability(ChromeOptions.CAPABILITY, chromeOptions);
WebDriver driver = new RemoteWebDriver(new URL("http://localhost:9515"), capabilities);
((RemoteWebDriver) driver).setSessionId(chromeSessionId);
// navigate to a URL using the attached Chrome window
driver.get("https://www.google.com");
}
}
```
In this code, the `chromeSessionId` variable stores the session ID of the open Chrome window. You can obtain the session ID by running the command `chrome://version/` in the address bar of the open Chrome window and looking for the value of the `Remote debugging port` field.
0 comments:
Post a Comment