Cypress调用reCaptcha-v3遇CSP错误,如何获取reCaptcha令牌?
解决Cypress中reCaptcha的Content Security Policy错误
问题原因
当前页面的Content Security Policy(CSP)仅允许script-src 'unsafe-eval',未将谷歌reCaptcha相关脚本域名加入允许列表,导致加载https://www.google.com/recaptcha/api.js时被拦截。
解决方案
方法1:修改Cypress全局配置
在cypress.config.js(或cypress.config.ts)中,更新contentSecurityPolicy配置,将谷歌相关域名加入脚本、框架、样式的允许列表:
export default defineConfig({ e2e: { // 保留原有其他配置 contentSecurityPolicy: { directives: { 'script-src': [ "'unsafe-eval'", "'self'", "https://www.google.com", "https://www.gstatic.com" ], 'frame-src': [ "https://www.google.com" ], 'style-src': [ "'self'", "'unsafe-inline'", "https://www.gstatic.com" ] } } } });
方法2:动态修改页面CSP头(适用于无法修改全局配置的场景)
在测试步骤执行前,通过cy.intercept拦截页面请求,修改响应头中的CSP规则:
Then('retrieve reCaptacha token', function () { // 拦截页面请求并修改CSP头 cy.intercept('GET', '/', (req) => { req.continue((res) => { res.headers['content-security-policy'] = `script-src 'unsafe-eval' 'self' https://www.google.com https://www.gstatic.com; frame-src https://www.google.com; style-src 'self' 'unsafe-inline' https://www.gstatic.com`; }); }); // 原有获取reCaptcha令牌的代码 load('<sitekey>').then((recaptcha) => { cy.log(recaptcha.getSiteKey()) recaptcha .execute('submit') .then((token) => { cy.log(token); }).catch((err) => { cy.log(err) }); }).catch((err) => { cy.log(err) }) });
补充说明
- 谷歌reCaptcha的资源分散在
www.google.com(主脚本)和www.gstatic.com(样式、静态资源),两个域名都需要加入允许列表。 - 若测试环境已有自定义CSP规则,需在原有规则基础上合并添加上述域名,避免完全覆盖原有配置。
内容的提问来源于stack exchange,提问作者mindparse
相关产品推荐
相关产品推荐

