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

Chrome阻止Next.js应用iframe渲染,配置next.config.js无效如何解决?

Next.js iframe在Chrome中被拦截的问题修复

配置中的问题点

  • CSP规则冗余且不精确:同时配置child-src和frame-src,Chrome优先遵循frame-src但child-src的example.com规则可能干扰解析;default-src使用*既不安全,还可能与具体规则冲突,Chrome对CSP的解析比Firefox更严格。
  • Sandbox权限不足:仅设置allow-scripts无法满足Chrome加载外部PDF的权限要求,Firefox权限限制相对宽松,因此能正常渲染。
  • 无效的X-Frame-Options配置:将该头设为空字符串无意义,Chrome会忽略并可能触发默认的同源限制。

修复后的next.config.js

const ContentSecurityPolicy = `
  default-src 'self';
  script-src 'self';
  style-src 'self' 'unsafe-inline';
  font-src 'self';  
  frame-src 'self' https://www.w3.org;
  object-src 'self' blob:;
`

const nextConfig = {
  experimental: {
    appDir: true,
  },
  async headers() {
    return [
      {
        source: '/:path*',
        headers: [
          {
            key: "Content-Security-Policy",
            value: ContentSecurityPolicy.replace(/\s{2,}/g, " ").trim(),
          },
        ],
      },
    ];
  },
};

module.exports = nextConfig;

调整后的iframe代码

<iframe
  sandbox="allow-scripts allow-same-origin"
  className={styles.iframe}
  src='https://www.w3.org/WAI/ER/tests/xhtml/testfiles/resources/pdf/dummy.pdf'
  title="dummy report"
></iframe>

修复说明

  • 精简CSP规则:移除冗余的child-src,将frame-src精确指定为目标PDF的域名https://www.w3.org,避免通配符带来的安全风险和解析问题。
  • 补充Sandbox权限:添加allow-same-origin,让Chrome允许iframe加载外部PDF资源。
  • 删除无效配置:移除X-Frame-Options的空值设置,避免触发默认限制。

内容的提问来源于stack exchange,提问作者Khant Min Si Thu

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.30 11:22:31