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

在localhost运行Selenium时,如何绕过Chrome剪贴板权限弹窗?

问题

使用Selenium搭配ChromeDriver测试本地localhost网站时,触发页面的Clipboard API会弹出权限请求框,需要无需用户干预自动授权剪贴板权限。尝试了多种ChromeOptions配置均无效,调用SetPermission方法时出现错误:

OneTimeSetUp: OpenQA.Selenium.WebDriverArgumentException : invalid argument: Permission can't be granted to opaque origins. (Session info: chrome=119.0.6045.105)

已知localhost被判定为不透明源,如何绕过这个权限提示?

尝试过的无效代码

var opts = new ChromeOptions();
opts.AddArgument("start-maximized");
//opts.AddUserProfilePreference("profile.default_content_settings.popups", 0);
//opts.AddUserProfilePreference("profile.default_content_settings.notifications", 1);
//opts.AddUserProfilePreference("profile.default_content_setting_values.notifications", 1);
//opts.AddUserProfilePreference("profile.default_content_setting_values.clipboard-read", 1);
//opts.AddUserProfilePreference("profile.default_content_setting_values.clipboard-write", 1);
//opts.AddUserProfilePreference("profile.content_settings.exceptions.clipboard", "*={'setting': 1}");
var chrm = new ChromeDriver(@"D:\Projects\General", opts);
//chrm.SetPermission("clipboard-read", "granted");
//chrm.SetPermission("clipboard-write", "granted");
driver = chrm;

解决方案

针对localhost本地源的剪贴板权限问题,以下是两种可靠解决方式:

1. 添加Chrome命令行参数直接授权

添加启动参数跳过剪贴板权限交互,对localhost完全有效:

var opts = new ChromeOptions();
opts.AddArgument("start-maximized");
// 核心参数:无需用户操作直接允许剪贴板访问
opts.AddArgument("--clipboard-access-policy=no-user-gesture-required");
// 可选:针对HTTPS本地站点的额外配置
opts.AddArgument("--allow-insecure-localhost");

var chrm = new ChromeDriver(@"D:\Projects\General", opts);
driver = chrm;

--clipboard-access-policy=no-user-gesture-required参数会强制浏览器允许页面直接读写剪贴板,无需用户确认。

2. 使用预配置的Chrome用户文件

如果命令行参数无效,可通过自定义用户配置文件实现权限持久化:

  1. 手动打开Chrome,创建新用户配置
  2. 访问localhost站点,手动允许剪贴板权限后关闭Chrome
  3. 在代码中指定该配置目录:
var opts = new ChromeOptions();
opts.AddArgument("start-maximized");
// 替换为你的自定义配置文件路径
opts.AddArgument(@"--user-data-dir=C:\Users\YourName\AppData\Local\Google\Chrome\User Data\CustomProfile");

var chrm = new ChromeDriver(@"D:\Projects\General", opts);
driver = chrm;

这种方式会复用手动配置的权限设置,不会再弹出请求框。

内容的提问来源于stack exchange,提问作者Yisroel M. Olewski

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.06 15:22:36