当我尝试从 Chrome 扩展程序的后台脚本发出请求时,我收到了 CORS 错误。后台脚本与 webpack 捆绑在一起。
注意:如果我转换manifest.json
为版本 2 - 一切正常。但是对于 v3,它给出了
CORS 策略已阻止从源“chrome-extension://exampleid”获取“https://example.com/api/user/login”的访问权限:不存在“Access-Control-Allow-Origin”标头在请求的资源上。如果不透明的响应满足您的需求,请将请求的模式设置为“no-cors”以获取禁用 CORS 的资源。
manifest.json
{
"name": "__CE_APP_NAME__",
"version": "__CE_APP_VERSION__",
"manifest_version": 3,
"background": {
"service_worker": "background.bundle.js",
"type": "module"
},
"content_scripts": [
{
"matches": [
"https://example.com/*"
],
"js": ["content.bundle.js"]
}
],
"web_accessible_resources": [
{
"resources": [ "images/*", "*.css" ],
"matches": [
"https://example.com/*"
]
}
],
"permissions": [
"storage",
"unlimitedStorage",
"cookies",
"identity"
],
"host_permissions": [
"<all_urls>"
]
}
background.js
chrome.runtime.onMessage.addListener((req) => {
if (req.type === 'auth/login') {
login(req.payload);
}
return true;
});
interface LoginCredentials {
email: string;
password: string;
}
const login = (data: LoginCredentials) => {
fetch(`${API_BASE_URL}/user/login`, {
method: 'POST',
body: new URLSearchParams({
email: data.email,
password: data.password
})
})
.then((response) => console.log(response))
.catch((error) => console.log(error));
};