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

Posted

技术标签:

【中文标题】如何使用 Selenium for Firefox 和 Chrome 禁用推送通知?【英文标题】:How to disable push-notifications using Selenium for Firefox and Chrome? 【发布时间】:2018-09-19 09:06:15 【问题描述】:

我想在通过 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>

【问题讨论】:

【参考方案1】:

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

要在 Firefox 浏览器客户端中禁用 Push Notification,请借助 FirefoxProfile 并传递 Keys dom.webnotifications.enabled dom.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.notificationsValue2

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

【讨论】:

这适用于 Firefox,但我更改了一行:FirefoxProfile testprofile = profile.getProfile("default"); 这是通用解决方案吗?我的队友可以在其他主机/操作系统上使用它吗? @vixsimplex 我在 cmets 中添加了关于您的问题的参考。然而,根据最佳实践,避免使用 default FirefoxProfile,因为它可能包含 add-onsbookmarks 等。因此,您在加载 default 配置文件时可能会遇到 超时错误 @DebanjanB 我已经为 chrome 使用了这个解决方案,但通知仍然是“xxxx 想要显示通知”。 ***.com/questions/57015268/…可以看看吗?

以上是关于如何使用 Selenium for Firefox 和 Chrome 禁用推送通知?的主要内容,如果未能解决你的问题,请参考以下文章

使用 Selenium WebDriver for Firefox 下载 pdf

如何隐藏 Firefox 窗口(Selenium WebDriver)?

如何通过 Python 使用 GeckoDriver 和 Firefox 使 Selenium 脚本无法检测?

如何使用 Geckodriver 在 Selenium 中禁用 Firefox 登录?

Selenium:如何使用 firefox 和 python 禁用图像加载?

如何在 Python 中使用 Selenium 在 Firefox 中禁用 Flash?