How to Open a New Tab in Incognito Mode in Selenium Automation
Benefits of using incognito mode in Selenium automation, such as testing without cookies, cache, or saved session data.
1. Using ChromeOptions:
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
public class IncognitoModeExample {
public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver", "path_to_chromedriver");
ChromeOptions options = new ChromeOptions();
options.addArguments("--incognito");
WebDriver driver = new ChromeDriver(options);
driver.get("https://example.com");
}
}
2. Opening a New Tab in Selenium:
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
public class NewTabInIncognito {
public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver", "path_to_chromedriver");
ChromeOptions options = new ChromeOptions();
options.addArguments("--incognito");
WebDriver driver = new ChromeDriver(options);
driver.get("https://example.com");
// Open a new tab
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("window.open('https://google.com', '_blank');");
}
}
3.0pen a new Chrome browser instance from your Selenium automation and switch control to that new instance:
Step 1: Create a Utility Class for Chrome Instances
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
public class BrowserManager {
private WebDriver driver;
// Constructor to initialize a Chrome instance
public BrowserManager(boolean isIncognito) {
System.setProperty("webdriver.chrome.driver", "path_to_chromedriver");
ChromeOptions options = new ChromeOptions();
if (isIncognito) {
options.addArguments("--incognito"); // Enable incognito mode if required
}
driver = new ChromeDriver(options);
}
// Getter to retrieve the WebDriver instance
public WebDriver getDriver() {
return driver;
}
// Method to quit the browser
public void quitBrowser() {
if (driver != null) {
driver.quit();
}
}
}
Step 2: Use the Utility Class in Your Main Code
Utility Class (BrowserManager
):
- Encapsulates the logic for initializing Chrome browser instances.
- Accepts a parameter (
isIncognito
) to customize browser options, e.g., enabling incognito mode.
Benefits:
- Separation of Concerns: Initialization logic is isolated in the
BrowserManager
class.
- Reusability: The
BrowserManager
class can be reused across your project.
- Flexibility: Easily configure different browser options by extending the utility class.
Comments
Post a Comment