一个浏览器扩展解决方案,让 Vue3 应用能够绕过 CORS 限制进行跨域请求。
- ✅ 完全绕过 CORS 限制 - 通过浏览器扩展的特权环境发起请求
- ✅ 支持自定义 Header - 可传递 SSO Token、自定义认证信息等
- ✅ 无需后端服务器 - 纯前端 + 扩展方案
- ✅ TypeScript 支持 - 完整的类型提示
- ✅ 开箱即用 - 简单配置即可运行
.
├── extension/ # 浏览器扩展代码
│ ├── manifest.json # 扩展配置文件
│ ├── background.js # 后台脚本(发起实际请求)
│ └── content-script.js # 内容脚本(网页与扩展的桥梁)
└── vue3-app/ # Vue3 示例应用
├── src/
│ ├── utils/extensionProxy.ts # 封装的请求工具
│ └── views/HomePage.vue # 示例页面
└── ...
- 打开 Chrome/Edge 浏览器,访问
chrome://extensions/ - 开启右上角的 "开发者模式"
- 点击 "加载已解压的扩展程序"
- 选择本项目的
extension文件夹 - 确保扩展已启用
重要配置:修改 extension/manifest.json:
{
"host_permissions": [
"https://your-target-api.com/*" // 改成你的目标 API 域名
],
"content_scripts": [
{
"matches": [
"http://localhost:*/*", // 开发环境
"https://your-domain.com/*" // 生产环境
],
...
}
]
}cd vue3-app
npm install
npm run dev访问 http://localhost:3000
在页面上:
- 输入目标 API 地址
- 选择请求方法(GET/POST/PUT/DELETE)
- 添加 Authorization Header(如果需要)
- 点击"发送请求"
- 查看响应结果
将 vue3-app/src/utils/extensionProxy.ts 复制到你的项目中。
import extensionProxy from '@/utils/extensionProxy'
// GET 请求
const result = await extensionProxy.get(
'https://api.example.com/user/info',
{
'Authorization': 'Bearer your-sso-token'
}
)
if (result.success) {
console.log('数据:', result.data)
} else {
console.error('错误:', result.error)
}const result = await extensionProxy.post(
'https://api.example.com/submit',
{
name: 'test',
value: 123
},
{
'Authorization': 'Bearer your-sso-token',
'Content-Type': 'application/json'
}
)const result = await extensionProxy.request({
url: 'https://api.example.com/endpoint',
method: 'POST',
headers: {
'Authorization': 'Bearer token',
'X-Custom-Header': 'value'
},
body: { key: 'value' },
timeout: 10000 // 10秒超时
})Vue3 网站 扩展后台 目标 API
(你的页面) (background.js) (跨域服务器)
│ │ │
│ 1. 发送请求 │ │
│ ──────────────────> │ │
│ │ 2. fetch 请求 │
│ │ ──────────────────> │
│ │ │
│ │ 3. 返回数据 │
│ │ <────────────────── │
│ 4. 回传数据 │ │
│ <──────────────────│ │
- Content Script 注入到你的网页,建立通信桥梁
- Background Script 在扩展后台发起实际的网络请求
- 扩展拥有特权,可以绕过浏览器的 CORS 限制
- 数据通过消息传递返回到你的网页
检查扩展是否已安装并就绪。
const isReady = await extensionProxy.checkExtension()
if (!isReady) {
alert('请先安装扩展!')
}发起请求。
参数:
interface ProxyRequestOptions {
url: string
method?: 'GET' | 'POST' | 'PUT' | 'DELETE' | 'PATCH'
headers?: Record<string, string>
body?: any
timeout?: number // 默认 30000ms
}返回:
interface ProxyResponse<T = any> {
success: boolean
status?: number
statusText?: string
data?: T
error?: string
}extensionProxy.get(url, headers)
extensionProxy.post(url, body, headers)
extensionProxy.put(url, body, headers)
extensionProxy.delete(url, headers)- 扩展权限:
host_permissions必须包含目标 API 域名 - Content Script 匹配:
matches必须包含你的网站域名 - 用户安装:只有安装了扩展的用户才能使用此功能
- 安全性:不要在扩展中硬编码敏感信息
- 目标站限制:某些网站可能有额外的防爬措施
- 不要使用
<all_urls>,只授权必要的域名 - Token 等敏感信息应从用户登录态动态获取
- 生产环境建议发布到 Chrome Web Store
- 定期更新扩展以修复安全漏洞
MIT
欢迎提交 Issue 和 Pull Request!