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

Chrome扩展Manifest V3移除X-Frame-Options Header失效问题

解决Chrome扩展Manifest V3中移除X-Frame-Options Header失效的问题

你的代码存在几个关键问题,导致规则未生效,以下是修正方案:

1. 未实际添加规则到declarativeNetRequest

当前chrome.declarativeNetRequest.updateDynamicRules只执行了移除规则的操作,但没有添加你定义好的规则,需要在参数中加入addRules数组。

2. ResourceTypes设置错误

你要加载的是iframe,对应的资源类型应该是sub_frame,而不是main_frame(main_frame指浏览器标签页的主页面)。

修正后的background.js代码

// Background.js - JavaScript for background script

// Define a declarative net request rule to modify response headers
const rule = {
  id: 1,
  priority: 1,
  action: {
    type: 'modifyHeaders',
    responseHeaders: [
      {
        header: 'X-Frame-Options',
        operation: 'remove',
      },
      // 额外处理可能阻止iframe的CSP头部
      {
        header: 'Content-Security-Policy',
        operation: 'remove',
      },
    ],
  },
  condition: {
    urlFilter: '<all_urls>',
    resourceTypes: ['sub_frame'], // 修改为子框架类型
  },
};

// 先移除旧规则,再添加新规则
chrome.declarativeNetRequest.updateDynamicRules({
  removeRuleIds: [1],
  addRules: [rule] // 新增这一行
}, () => {
  if (chrome.runtime.lastError) {
    console.error('Error updating rules: ' + chrome.runtime.lastError);
  } else {
    console.log('Rule updated successfully');
  }
});

额外注意事项

  • 部分网站会通过Content-Security-Policy的frame-ancestors或frame-src指令限制iframe嵌入,所以需要同时移除或修改该头部(上面代码已包含移除操作)。
  • 确保host_permissions和permissions中包含<all_urls>,你的manifest已经配置正确,但如果是指定网站,可以缩小范围提升安全性。
  • 测试时需要重新加载扩展,并在Chrome开发者工具的Declarative Net Request面板(扩展的background service worker的DevTools中)查看规则是否成功添加。

内容的提问来源于stack exchange,提问作者VIc Pitic

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.11 06:35:25