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

Chrome扩展AJAX请求遭CORS拦截问题求助

解决Chrome扩展Manifest V3中的CORS跨域请求问题

你的popup页面属于chrome-extension://协议的源,直接向第三方域名发起AJAX请求时,浏览器会执行CORS检查,而目标服务器未返回Access-Control-Allow-Origin头,因此请求被拦截。在Manifest V3中,扩展处理跨域请求有两种可靠方案:

方案一:添加Host权限到Manifest

直接在manifest.json中配置目标域名的访问权限,Chrome会允许扩展绕过普通网页的CORS限制:

修改后的manifest.json:

{
  "manifest_version": 3,
  "name": "Zanelo Extension",
  "author": "Kim Ramirez",
  "description": "",
  "version": "1.0.0",
  "permissions": [
    "storage",
    "contextMenus"
  ],
  // 添加目标域名的Host权限
  "host_permissions": [
    "https://app.zanelo.io/*"
  ],
  "minimum_chrome_version": "92",
  "action": {
    "default_title": "Zanelo Extension",
    "default_popup": "popup.html"
  },
  "web_accessible_resources": [{
      "resources": [ "zanelo_icon.png","cog.png" ],
      "matches": [ "<all_urls>" ]
  }]
}

同时优化popup.js的AJAX代码,让jQuery自动解析JSON响应:

$.ajax({
  type: "GET",
  url: "https://app.zanelo.io/chrome_extension/par12134/par12341243143",
  dataType: "json", // 自动解析JSON,无需手动调用JSON.parse
  success: function(data) {
    alert(data.html);
  },
  error: function(error) {
    console.log(error);
  }
});

方案二:通过Background Service Worker代理请求

如果目标服务器有额外的来源校验,可通过扩展的后台服务工作者发起请求(后台环境不受前端CORS限制):

  1. 更新manifest.json,注册后台服务工作者:
{
  // ... 现有字段
  "background": {
    "service_worker": "background.js"
  },
  "host_permissions": [
    "https://app.zanelo.io/*"
  ]
}
  1. 创建background.js,添加消息监听与请求代理逻辑:
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
  if (request.action === 'fetchData') {
    fetch(request.url)
      .then(response => response.json())
      .then(data => sendResponse(data))
      .catch(error => sendResponse({error: error.message}));
    return true; // 标记异步响应
  }
});
  1. 修改popup.js,改为向后台发送消息获取数据:
chrome.runtime.sendMessage({
  action: 'fetchData',
  url: "https://app.zanelo.io/chrome_extension/par12134/par12341243143"
}, function(response) {
  if (response.error) {
    console.log('请求失败:', response.error);
  } else {
    alert(response.html);
  }
});

最后,在Chrome扩展管理页面点击「重新加载」按钮,确保新配置生效。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 01:20:25