java - 如何使用 Selenium 为 Firefox 和 Chrome 禁用推送通知?

标签 java selenium selenium-webdriver selenium-chromedriver geckodriver

我想在通过 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 并传递 key dom.webnotifications。 enableddom.push.enabled 以及所需的 Valuefalse :

    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()来传递HashMap 包含 profile.default_content_setting_values.notifications2:

    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/");
    

关于java - 如何使用 Selenium 为 Firefox 和 Chrome 禁用推送通知?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59455249/

相关文章:

java - 在 jenkins 中使用 Docker 从站时,Selenium 驱动程序崩溃并给出 NoSuchSessionException

jquery - CSS 选择器对属性不区分大小写

c# - 无法在 Selenium 中启动 chrome 驱动程序

java - Android 中的 PNG ImageData 转位图

java 编译器与泛型和迭代器错误

python - Selenium Python ActionChain 预制方法

java - 我们如何在测试 Web 应用程序时打开多个 IE 实例。在 eclipse 中使用 selenium RC 和 java?

selenium-webdriver - 如何在 Selenium WebDriver 中导航后可靠地检查当前页面?

java - 异常类不工作

java - 具有 'must-pass' 个节点的 Dijkstra 算法