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

如何解决Cypress launchOptions配置Chromium通知权限不生效问题?

Cypress CI环境Chromium内核浏览器预开启通知权限配置不生效

问题描述

  • 场景:CI环境运行Cypress E2E测试,覆盖Chrome、Edge等Chromium内核浏览器与Firefox浏览器,部分用例执行失败。失败原因为测试逻辑需要stub站点发起的通知请求,但浏览器未预先获得通知发送权限,触发权限申请弹窗中断流程。
  • 已执行配置:参考Cypress官方浏览器启动API说明,在cypress.config.js中编写启动钩子配置权限,代码如下:
const { defineConfig } = require('cypress')

module.exports = defineConfig({
  e2e: {
    setupNodeEvents(on, config) {
      on('before:browser:launch', (browser, launchOptions) => {
        switch(browser.family) {
          case 'firefox':
            launchOptions.preferences.['permissions.default.desktop-notification'] = 1;
            break;
          case 'chromium':
            launchOptions.preferences.default['profile.default_content_settings_values.notifications'] = 1;
            launchOptions.preferences.default['profile.managed_default_content_settings.notifications'] = 1;
            break;
          }
        }
        return launchOptions;
      })
    }
  }
})
  • 预期结果:Firefox与Chromium内核浏览器均默认开启通知权限,不弹出权限申请提示。
  • 实际结果:Firefox配置生效符合预期,Chromium内核浏览器仍需手动交互才能授予通知权限。
  • 已排查动作:核对过同类问题方案、cypress-browser-permissions仓库实现、Chromium官方偏好设置文档,未解决问题。

解决方案

你的Chromium配置存在两处核心错误,修正后即可正常生效:

  1. 配置层级错误:Chromium内核浏览器的偏好配置直接挂载在launchOptions.preferences下,不需要嵌套default层级,多余嵌套会导致配置完全不被浏览器读取。
  2. 键名拼写错误:你使用的profile.default_content_settings_values.notifications键名多了一个s,正确键名为profile.default_content_setting_values.notifications,拼写错误会导致配置项无法被浏览器识别。
  3. 若在CI无头模式下运行,可追加启动参数绕过系统层的权限弹窗拦截,进一步提升稳定性。

修正后的完整配置代码如下:

const { defineConfig } = require('cypress')

module.exports = defineConfig({
  e2e: {
    setupNodeEvents(on, config) {
      on('before:browser:launch', (browser, launchOptions) => {
        switch(browser.family) {
          case 'firefox':
            launchOptions.preferences['permissions.default.desktop-notification'] = 1;
            break;
          case 'chromium':
            launchOptions.preferences['profile.default_content_setting_values.notifications'] = 1;
            launchOptions.preferences['profile.managed_default_content_settings.notifications'] = 1;
            // CI无头环境适配参数
            launchOptions.args.push('--disable-notification-prompt-for-testing');
            break;
          }
        }
        return launchOptions;
      })
    }
  }
})

注:配置值1代表默认允许通知,若需默认禁用通知可将值改为2。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.29 12:00:50