Puppeteer渲染HTTPS iframe触发CSP frame-ancestors报错如何解决?
问题原因
你使用page.setContent()注入页面内容时,页面默认使用about:blank协议,不符合目标iframe配置的CSP规则:frame-ancestors 'self' https:,该规则要求iframe的父页面必须使用HTTPS协议,因此请求被浏览器拦截。
解决方案
方案1:模拟HTTPS父页面(推荐)
无需额外启动本地服务,通过Puppeteer的请求拦截功能,将任意自定义HTTPS地址的响应替换为你的页面内容,保证父页面协议符合要求,完全遵循浏览器安全规则,兼容性最好。
修改后代码如下:
const puppeteer = require("puppeteer"); const embed = ` <iframe src="<some https url>" style="width: 330px; height: 186px; border: 0px;"></iframe> `; const timedPromise = time => new Promise(res => { setTimeout(() => { res() }, time); }); (async function () { const browser = await puppeteer.launch({ headless: false}); const page = await browser.newPage(); // 开启请求拦截 await page.setRequestInterception(true); page.on('request', (req) => { // 拦截自定义的测试HTTPS地址请求 if (req.url() === 'https://test.local/embed') { req.respond({ status: 200, contentType: 'text/html', body: embed }); } else { req.continue(); } }); // 访问该地址,父页协议为HTTPS符合CSP要求 await page.goto('https://test.local/embed'); await timedPromise(3000); await page.screenshot({ path: `screenshot${Number(Date.now())}.png` }); await browser.close(); })();
方案2:临时关闭CSP校验(仅测试用)
如果仅做本地快速测试,可以在启动浏览器时添加参数禁用安全策略,跳过CSP校验。
仅需修改浏览器启动配置即可:
const browser = await puppeteer.launch({ headless: false, // 禁用安全策略,仅本地测试可用 args: ['--disable-web-security', '--disable-features=ContentSecurityPolicy'] });
注意:该方案会关闭浏览器的跨域、CSP等所有安全校验,存在安全风险,仅可用于本地测试场景,不可在生产环境或访问不可信内容时使用。
内容的提问来源于stack exchange,提问作者OliverRadini
相关产品推荐
相关产品推荐

