How to avoid the pop-up window in chrome browser with Selenium?


We can avoid the pop-up window in Chrome browser with Selenium webdriver using the ChromeOptions class. We have to create an object of this class and apply the setExperimentalOption method to it. We shall create a Map and insert the below Chrome browser preference to it −

profile.default_content_setting_values.notifications, and set its value to 2.

The above browser preference shall be passed as a parameter to the method setExperimentalOption and finally added to the webdriver object.

Syntax

Map<String, Object> pf = new HashMap<String, Object>();
pf.put("profile.default_content_setting_values.notifications", 2);
ChromeOptions p = new ChromeOptions();
p.setExperimentalOption("prefs", pf);

Example

import org.openqa.selenium.By;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import java.util.HashMap;
import java.util.Map;
import org.openqa.selenium.WebDriver;
public class PopupDisable {
   public static void main(String[] args) throws IOException {
      System.setProperty("webdriver.chrome.driver",
         "C:\Users\ghs6kor\Desktop\Java\chromedriver.exe");
      //Map creation
      Map<String, Object> pf = new HashMap<String, Object>();
      // disable pop up browser preference added to Map
      pf.put("profile.default_content_setting_values.notifications", 2);
      //object of ChromeOptions
      ChromeOptions p = new ChromeOptions();
      p.setExperimentalOption("prefs", pf);
      // pass browser option to webdriver
      WebDriver driver = new ChromeDriver(p);
      //implicit wait
      driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
      //URL launch
      driver.get("https://www.tutorialspoint.com/index.htm");
      System.out.println("Pop-up blocked");
      //browser quit
      driver.quit();
   }
}

Output

Updated on: 07-Apr-2021

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements