如何在Selenium+JavaScript自动化测试中启用剪贴板权限弹窗?
问题:Selenium WebDriver + JavaScript 中剪贴板权限配置(setting:1)无效果
如何在使用Selenium WebDriver和JavaScript的自动化测试中启用/允许剪贴板权限弹窗?

测试发现,通过Chrome配置项设置剪贴板权限时,setting值为0和2时功能符合预期,但设置为1时无任何反应:
- setting:0:弹窗正常显示,配置代码:
setProperty(testOptions, 'desiredCapabilities/goog:chromeOptions/prefs/profile.content_settings.exceptions.clipboard', { '*': { setting: 0 } });
- setting:1:无任何反应,配置代码:
setProperty(testOptions, 'desiredCapabilities/goog:chromeOptions/prefs/profile.content_settings.exceptions.clipboard', { '*': { setting: 1 } });
- setting:2:弹窗被正常拦截,配置代码:
setProperty(testOptions, 'desiredCapabilities/goog:chromeOptions/prefs/profile.content_settings.exceptions.clipboard', { '*': { setting: 2 } });
解决方法
Chrome的profile.content_settings.exceptions.clipboard配置在部分版本中对setting:1的支持存在兼容性问题,可尝试以下几种有效方案:
1. 使用命令行参数直接授予权限
通过Chrome启动参数直接开启剪贴板读写权限,跳过弹窗确认:
setProperty(testOptions, 'desiredCapabilities/goog:chromeOptions/args', [ '--clipboard-access-policy=no-user-gesture-required', '--enable-clipboard-read', '--enable-clipboard-write' ]);
2. 完善内容设置配置结构
给剪贴板例外配置添加last_modified时间戳,同时设置默认权限值,确保Chrome识别配置更新:
// 设置默认剪贴板权限为允许 setProperty(testOptions, 'desiredCapabilities/goog:chromeOptions/prefs/profile.content_settings.default_content_setting_values.clipboard', 1); // 配置全局剪贴板例外并添加时间戳 setProperty(testOptions, 'desiredCapabilities/goog:chromeOptions/prefs/profile.content_settings.exceptions.clipboard', { '*': { setting: 1, last_modified: Date.now() } });
3. 通过Chrome DevTools Protocol(CDP)设置权限
利用CDP直接向浏览器授予剪贴板权限,这种方式兼容性最好:
// 初始化driver后执行 const driver = await new Builder().forBrowser('chrome').setChromeOptions(chromeOptions).build(); // 授予当前页面剪贴板读写权限 await driver.executeCdpCommand('Browser.grantPermissions', { permissions: ['clipboardRead', 'clipboardWrite'], origin: await driver.getCurrentUrl() });
内容的提问来源于stack exchange,提问作者pavankc
相关产品推荐
相关产品推荐

