You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Selenium(JavaScript)如何禁用Chrome通知面板?

解决Selenium JavaScript中Chrome通知弹窗无法禁用的问题

问题分析

你尝试通过--disable-notifications命令行参数禁用通知但未生效,核心原因大概率是ChromeOptions的配置方式不符合当前Selenium版本要求,或是缺少更底层的权限偏好设置来强制拦截通知请求。

解决方案

方案1:适配官方新版selenium-webdriver包

如果项目使用的是官方最新版selenium-webdriver,请使用Options类完成配置,而非直接操作Capabilities:

const { Builder } = require('selenium-webdriver');
const chrome = require('selenium-webdriver/chrome');

async function initDriver() {
  // 创建Chrome配置实例
  const chromeOptions = new chrome.Options();
  // 添加禁用通知的命令行参数
  chromeOptions.addArguments('--disable-notifications');
  // 追加偏好设置,从浏览器层面强制拒绝所有通知请求
  chromeOptions.setUserPreferences({
    'profile.default_content_setting_values.notifications': 2 // 2代表"拒绝"权限
  });

  // 构建并返回驱动
  return await new Builder()
    .forBrowser('chrome')
    .setChromeOptions(chromeOptions)
    .build();
}

// 调用初始化逻辑
initDriver().then(driver => {
  // 后续测试代码...
});

方案2:适配旧版wd类Selenium包

如果项目使用的是旧版wd类包,需调整Capabilities的配置键名,确保参数被正确识别:

const webdriver = require('wd');

const chromeCapabilities = webdriver.Capabilities.chrome();
const chromeOptions = {
  args: ['--disable-notifications'],
  prefs: {
    'profile.default_content_setting_values.notifications': 2
  }
};
// 新版WebDriver规范要求使用'goog:chromeOptions'作为配置键
chromeCapabilities.set('goog:chromeOptions', chromeOptions);

// 初始化驱动
const driver = webdriver.promiseChainRemote();
driver.init(chromeCapabilities);

关键注意点

  • profile.default_content_setting_values.notifications = 2是Chrome内置的权限配置,直接从浏览器层面拦截通知请求,比命令行参数的优先级更高、可靠性更强。
  • 部分新版Chrome必须使用goog:chromeOptions作为配置键,而非旧版的chromeOptions,这是W3C WebDriver规范的强制要求。

内容的提问来源于stack exchange,提问作者Chaffe

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.15 18:40:32