如何使用 Selenium for Firefox 和 Chrome 禁用推送通知?

How to disable push-notifications using Selenium for Firefox and Chrome?

我想在通过 Selenium Webdriver 启动 Firefox 浏览器时禁用通知。
我找到了 this answer,但它已被弃用并且不适用于我在 Firefox 上的工作(尽管它在 Chrome 上工作得很好)。

我正在为我的 pom.xml 使用此依赖项:

<dependency>
    <groupId>org.seleniumhq.selenium</groupId>
    <artifactId>selenium-java</artifactId>
    <version>3.11.0</version>
</dependency>

如果您的 用例 是禁用 通知 以下是选项:

  • 要在 Firefox 浏览器客户端中禁用 Push Notification 需要 FirefoxProfile 的帮助并传递 Keys dom.webnotifications.enableddom.push.enabled 以及所需的 :

    System.setProperty("webdriver.gecko.driver", "C:\path\to\geckodriver.exe");
    ProfilesIni profile = new ProfilesIni();
    FirefoxProfile testprofile = profile.getProfile("debanjan");
    testprofile.setPreference("dom.webnotifications.enabled", false);
    testprofile.setPreference("dom.push.enabled", false);
    DesiredCapabilities dc = DesiredCapabilities.firefox();
    dc.setCapability(FirefoxDriver.PROFILE, testprofile);
    FirefoxOptions opt = new FirefoxOptions();
    opt.merge(dc);
    WebDriver driver =  new FirefoxDriver(opt);
    driver.get("https://www.ndtv.com/");
    

注意 :此方法使用名称为 debanjan 的现有 FirefoxProfile 存储在我的本地系统中,该系统创建如下Creating a new Firefox profile on Windows

处的文档
  • 要在 Chrome 浏览器客户端中禁用 通知 setExperimentalOption() 传递包含 profile.default_content_setting_values.notificationsValueHashMap作为 2 :

    System.setProperty("webdriver.chrome.driver", "C:\path\to\chromedriver.exe");
    Map<String, Object> prefs = new HashMap<String, Object>();
    prefs.put("profile.default_content_setting_values.notifications", 2);
    prefs.put("credentials_enable_service", false);
    prefs.put("profile.password_manager_enabled", false);
    ChromeOptions options = new ChromeOptions();
    options.setExperimentalOption("prefs", prefs);
    options.addArguments("start-maximized");
    options.addArguments("disable-infobars");
    options.addArguments("--disable-extensions");
    options.addArguments("--disable-notifications");
    WebDriver driver = new ChromeDriver(options);
    driver.get("https://www.ndtv.com/");