Open Edge in InPrivate mode using Selenium

2019-02-18 16:34发布

问题:

I am using Selenium 3.4 to launch Edge using the Microsoft WebDriver which is now maintained by Microsoft.

Is there any way I can launch the Browser in InPrivate mode using Selenium?

I have searched for answers but couldn't find any.

The closest I got was How to start Edge browser in Incognito mode using selenium remote webdriver?

The solution mentioned there doesn't work. It just shows the same tab as would be shown in InPrivate, but the window isn't a private one. As such, the information is stored and the session is not private.

回答1:

Use the below code, employing java.awt.Robot to simulate the key combination CTRL+SHIFT+P to open a new browser window in InPrivate mode:

    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
}

Note that we are using robot class and so if the system locks it may not work.