How to open incognito/private window with Selenium WD for different browser types?
Asked Answered
M

10

18

I want to test my test cases in private window or incognito window.

How to do the same in various browsers:

  • firefox (prefered)
  • chrome (prefered)
  • IE
  • safari
  • opera

How to achieve it?

Melchor answered 19/10, 2015 at 21:16 Comment(1)
Possible duplicate of Run chrome browser in inconginto Mode in SeleniumAnalisaanalise
B
26
  • Chrome:

    DesiredCapabilities capabilities = DesiredCapabilities.chrome();
    ChromeOptions options = new ChromeOptions();
    options.addArguments("incognito");
    capabilities.setCapability(ChromeOptions.CAPABILITY, options);
    
  • FireFox:

    FirefoxProfile firefoxProfile = new FirefoxProfile();    
    firefoxProfile.setPreference("browser.privatebrowsing.autostart", true);
    
  • Internet Explorer:

    DesiredCapabilities capabilities = DesiredCapabilities.internetExplorer();
    capabilities.setCapability(InternetExplorerDriver.FORCE_CREATE_PROCESS, true); 
    capabilities.setCapability(InternetExplorerDriver.IE_SWITCHES, "-private");
    
  • Opera:

    DesiredCapabilities capabilities = DesiredCapabilities.operaBlink();
    OperaOptions options = new OperaOptions();
    options.addArguments("private");
    capabilities.setCapability(OperaOptions.CAPABILITY, options);
    
Bronez answered 31/3, 2016 at 11:58 Comment(4)
For future visitor- this does not work with selenium 2.53, works with 2.52.Opalopalesce
Which points don't work? We use Selenium 3.0.1 and everything works correctly.Bronez
Yes it works with 3.0.1, Sadly I am not able(read allowed) to upgrade to the latest version. I've wasted more than 2 hours So i thought it might be beneficial for someone facing same issue.Opalopalesce
The above code for Firefox, is not working in my caseTreva
B
16

In chrome you can try using -incognito command line switch in options, not sure if there will be a problem with automation extension but worth a try.

ChromeOptions options = new ChromeOptions();
options.addArguments("incognito");

For FireFox, a special flag in the profile can be used for the purpose

FirefoxProfile firefoxProfile = new FirefoxProfile();    
firefoxProfile.setPreference("browser.private.browsing.autostart",true);

For IE

setCapability(InternetExplorerDriver.IE_SWITCHES, "-private");
Barnsley answered 19/10, 2015 at 21:54 Comment(1)
The above code for firefox is not working in my case.Treva
S
4
FirefoxOptions opts = new FirefoxOptions();
opts.addArguments("-private");
FirefoxDrive f = new FirefoxDriver(opts);

This works fine for selenium version 3.14.0 and geckodriver-v0.22.0

Seizure answered 26/9, 2018 at 19:0 Comment(0)
R
1
public class gettext {
  static WebDriver driver= null;

  public static void main(String args[]) throws InterruptedException {

    //for private window

    DesiredCapabilities capabilities = DesiredCapabilities.chrome();
    ChromeOptions option = new ChromeOptions();
    option.addArguments("incognito");
    capabilities.setCapability(ChromeOptions.CAPABILITY,option);
    System.setProperty("webdriver.chrome.driver", "D:\\Tools\\chromedriver.exe");       
    driver= new ChromeDriver(capabilities);

    String url = "https://www.google.com/";
    driver.manage().window().maximize();
    driver.get(url);
    driver.manage().timeouts().implicitlyWait(20,TimeUnit.SECONDS);
    gettextdata();
  } 
}
Respectability answered 14/5, 2018 at 13:20 Comment(0)
F
0

Find the body element on the page and then fire off a Key Chord to it for the browser you want. In the sample below I've tried to abstract the browsers to an enumeration that outline the behavior for newTab, newWindow and newIncognitoWindow. I made content FF, IE, Chrome, Safari, and Opera; however, they may not be fully implemented due to my lack of knowledge.

  /**
     * Enumeration quantifying some common keystrokes for Browser Interactions.
     * 
     * @see "https://mcmap.net/q/651681/-how-to-open-incognito-private-window-with-selenium-wd-for-different-browser-types"
     * @author http://stackoverflow.com/users/5407189/jeremiah
     * @since Oct 19, 2015
     *
     */
    public static enum KeystrokeSupport {
        CHROME,
        FIREFOX {
            @Override
            protected CharSequence getNewIncognitoWindowCommand() {
                return Keys.chord(Keys.CONTROL, Keys.SHIFT, "p");
            }
        },
        IE {
            @Override
            protected CharSequence getNewIncognitoWindowCommand() {
                return Keys.chord(Keys.CONTROL, Keys.SHIFT, "p");
            }
        },
        SAFARI {
            @Override
            protected CharSequence getNewTabCommand() {
                throw new UnsupportedOperationException("Author does not know this keystroke");
            }

            @Override
            protected CharSequence getNewWindowCommand() {
                throw new UnsupportedOperationException("Author does not know this keystroke");
            }

            @Override
            protected CharSequence getNewIncognitoWindowCommand() {
                throw new UnsupportedOperationException("Author does not know this keystroke");
            }
        },
        OPERA {
            @Override
            protected CharSequence getNewIncognitoWindowCommand() {
                throw new UnsupportedOperationException("Author does not know this keystroke");
            }
        };

        public final void newTab(WebDriver driver) {
            WebElement target = getKeystrokeTarget(driver);
            target.sendKeys(getNewTabCommand());
        }

        public final void newWindow(WebDriver driver) {
            WebElement target = getKeystrokeTarget(driver);
            target.sendKeys(getNewWindowCommand());
        }

        public final void newIncognitoWindow(WebDriver driver) {
            WebElement target = getKeystrokeTarget(driver);
            target.sendKeys(getNewIncognitoWindowCommand());
        }

        protected CharSequence getNewTabCommand() {
            return Keys.chord(Keys.CONTROL, "t");
        }

        protected CharSequence getNewWindowCommand() {
            return Keys.chord(Keys.CONTROL, "n");
        }

        protected CharSequence getNewIncognitoWindowCommand() {
            return Keys.chord(Keys.CONTROL, Keys.SHIFT, "t");
        }

        protected final WebElement getKeystrokeTarget(WebDriver driver) {
            WebDriverWait wait = new WebDriverWait(driver, 10);
            return wait.until(ExpectedConditions.presenceOfElementLocated(By.cssSelector("body")));
        }

    }

With that then, we can offer a Parameterized test that will run through each of the configurations and execute the behaviors for visual verification. You may want to add whatever asserts you want to the test.

package stackoverflow.proof.selenium;

import java.util.Collection;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameters;
import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;


import com.google.common.base.Supplier;
import com.google.common.collect.Lists;



/**
 * Test to try out some various browser keystrokes and try to get the environment to do what we want.
 * 
 * @see "https://mcmap.net/q/651681/-how-to-open-incognito-private-window-with-selenium-wd-for-different-browser-types"
 * @author http://stackoverflow.com/users/5407189/jeremiah
 * @since Oct 19, 2015
 *
 */
@RunWith(Parameterized.class)
public class KeyStrokeTests {


    @Parameters(name="{0}")
    public static Collection<Object[]> buildTestParams() {
        Collection<Object[]> params = Lists.newArrayList();
        Supplier<WebDriver> ffS = new Supplier<WebDriver>() {
            public WebDriver get() {
                return new FirefoxDriver();
            }
        };
        params.add(new Object[]{KeystrokeSupport.FIREFOX, ffS});

      /* I'm not currently using these browsers, but this should work with minimal effort.
        Supplier<WebDriver> chrome = new Supplier<WebDriver>() {
            public WebDriver get() {
                return new ChromeDriver();
            }
        };
        Supplier<WebDriver> ie = new Supplier<WebDriver>() {
            public WebDriver get() {
                return new InternetExplorerDriver();
            }
        };
        Supplier<WebDriver> safari = new Supplier<WebDriver>() {
            public WebDriver get() {
                return new SafariDriver();
            }
        };
        Supplier<WebDriver> opera = new Supplier<WebDriver>() {
            public WebDriver get() {
                return new OperaDriver();
            }
        };

        params.add(new Object[]{KeystrokeSupport.CHROME, chrome});
        params.add(new Object[]{KeystrokeSupport.IE, ie});
        params.add(new Object[]{KeystrokeSupport.SAFARI, safari});
        params.add(new Object[]{KeystrokeSupport.OPERA, opera});
        */
        return params;
    }
    Supplier<WebDriver> supplier;
    WebDriver driver;
    KeystrokeSupport support;

    public KeyStrokeTests(KeystrokeSupport support,Supplier<WebDriver> supplier) {
        this.supplier = supplier;
        this.support = support;
    }

    @Before
    public void setup() {
        driver = supplier.get();
        driver.get("http://google.com");
    }

    @Test
    public void testNewTab() {
        support.newTab(driver);
    }
    @Test
    public void testNewIncognitoWindow() {
        support.newIncognitoWindow(driver);
    }

    @Test
    public void testNewWindow() {
        support.newWindow(driver);
    }

    @After
    public void lookAtMe() throws Exception{
        Thread.sleep(5000);    
          for (String handle : driver.getWindowHandles()) {
            driver.switchTo().window(handle);
            driver.close();
        }
    }
  }

Best of Luck.

Finale answered 19/10, 2015 at 21:52 Comment(1)
I hate seing ideas, that could possibly work, but with few minus votes and no comments what is wrong with this one.Dumfries
M
0

For Chrome use this code to open the browser in incognito mode:

public WebDriver chromedriver;
ChromeOptions options = new ChromeOptions();
options.addArguments("-incognito");
DesiredCapabilities capabilities = DesiredCapabilities.chrome();
capabilities.setCapability(ChromeOptions.CAPABILITY, options);
WebDriver chromedriver=new ChromeDriver(capabilities);
chromedriver.get("url");
Monologue answered 29/10, 2016 at 15:26 Comment(0)
T
0
public static void OpenBrowser() {
    if (Browser.equals("Chrome")) {
        System.setProperty("webdriver.chrome.driver", "E:\\Workspace\\proj\\chromedriver.exe");
        DesiredCapabilities capabilities = DesiredCapabilities.chrome();
        ChromeOptions options = new ChromeOptions();
        options.addArguments("incognito");
        capabilities.setCapability(ChromeOptions.CAPABILITY, options);
        driver = new ChromeDriver(capabilities);
    } else if (Browser.equals("IE")) {

        DesiredCapabilities capabilities = DesiredCapabilities.internetExplorer();
        capabilities.setCapability(InternetExplorerDriver.FORCE_CREATE_PROCESS, false);
// if you get this exception "org.openqa.selenium.remote.SessionNotFoundException: " . uncomment the below line and comment the above line
// capabilities.setCapability(InternetExplorerDriver.FORCE_CREATE_PROCESS, true);
        System.setProperty("webdriver.ie.driver", "E:\\Workspace\\proj\\IEDriverServer32.exe");capabilities.setCapability(InternetExplorerDriver.IE_SWITCHES, "-private");
        driver = new InternetExplorerDriver(capabilities);
    } else {
        FirefoxProfile firefoxProfile = new FirefoxProfile();
        firefoxProfile.setPreference("browser.privatebrowsing.autostart", true);
        driver = new FirefoxDriver(firefoxProfile);
    }
Thumbtack answered 2/3, 2017 at 5:10 Comment(0)
D
0

I was able to run remote IE in private mode only after following updates:

InternetExplorerOptions options = new InternetExplorerOptions()
                    .ignoreZoomSettings()
                    .useCreateProcessApiToLaunchIe()
                    .addCommandSwitches("-private");

DesiredCapabilities capabilities = DesiredCapabilities.internetExplorer();
            capabilities.setCapability("se:ieOptions", options);
return new RemoteWebDriver(url, capabilities);

All of above didn't work for RemoteWebDriver.

Disloyalty answered 14/2, 2019 at 14:50 Comment(0)
C
0

How to avoid Extensions in Private Mode prompt

For the actual geckodriver version I use:

    options.addArguments("-private");

It works fine but the annoying notification appears: Extensions in Private Mode.

I found the way to avoid it:

    options.addPreference("extensions.allowPrivateBrowsingByDefault",true);

As a result all extensions will run in private browsing mode without prompting at start

Cock answered 4/12, 2019 at 8:49 Comment(0)
I
0

For other browser everyone has answered so for OPERA

OperaOptions options = new OperaOptions();
options.addArguments("private");
WebDriver driver = new OperaDriver(options);
driver.get("https://selenium.dev");
Isosceles answered 26/2, 2022 at 7:53 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.