使用以下代码,使用java.awt.Robot模拟组合键CTRL+SHIFT+P
以 InPrivate 模式打开新的浏览器窗口:
System.setProperty("webdriver.edge.driver","D:\\Workspace\\StackOverlow\\src\\lib\\MicrosoftWebDriver.exe"); //put actual location
WebDriver driver = new EdgeDriver();
driver.navigate().to("https://www.google.com");
driver.manage().window().maximize();
Robot robot;
try {
// This is the actual code that opens the InPrivate window
robot = new Robot();
robot.keyPress(KeyEvent.VK_CONTROL);
robot.keyPress(KeyEvent.VK_SHIFT);
robot.keyPress(KeyEvent.VK_P);
robot.keyRelease(KeyEvent.VK_CONTROL);
robot.keyRelease(KeyEvent.VK_SHIFT);
robot.keyRelease(KeyEvent.VK_P);
Thread.sleep(3000);
} catch (AWTException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String parentWindowHandler = driver.getWindowHandle();
String subWindowHandler = null;
Set<String> handles = driver.getWindowHandles();
Iterator<String> iterator = handles.iterator();
while (iterator.hasNext()){
subWindowHandler = iterator.next();
driver.switchTo().window(subWindowHandler);
System.out.println(subWindowHandler);
}
driver.get("https://stackoverflow.com/");
//driver.switchTo().window(parentWindowHandler); // Uncomment this line if you want to use normal browser back
}
请注意,我们正在使用机器人类,因此如果系统锁定它可能无法工作。