我正在开发 Edge 扩展,我需要从外部网站请求 JSON。以下示例在 stackoverflow.com 上运行良好,但在我需要的 steamcommunity.com/id/上失败。
这是我拥有的文件:
jQuery(来自本地文件)
manifest.json:
{
"author": "me",
"name": "Get JSON",
"description": "get json",
"version": "0.1",
"manifest_version": 2,
"content_scripts": [
{
"matches": [
"*://steamcommunity.com/id/*",
"*://stackoverflow.com/*"
],
"js": ["jquery.min.js", "myscript.js"]
}
]
}
myscript.js:
var url = 'https://raw.githubusercontent.com/bahamas10/css-color-names/master/css-color-names.json';
$.getJSON(url, function(data) {
console.log(data);
});
正如我所说,这个示例在 Stackoverflow 上运行良好,但在 Steam 上失败。
这是我在 Steam 网站上收到的错误:
CSP14312: Resource violated directive 'connect-src 'self' http://steamcommunity.com https://steamcommunity.com https://api.steampowered.com/ http://localhost:27060 http://store.steampowered.com/ https://store.steampowered.com/' in Content-Security-Policy: https://raw.githubusercontent.com/bahamas10/css-color-names/master/css-color-names.json. Resource will be blocked.
编辑:我还应该补充一点,在 Google Chrome 中使用 Chrome 扩展程序时,这个确切的示例工作正常。
如有任何帮助,我们将不胜感激。
最佳答案
与 Chrome 和 Firefox 不同,Microsoft Edge 不会忽略扩展程序的网站 CSP 规则。
参见https://developer.microsoft.com/en-us/microsoft-edge/platform/issues/11320214/对于一个悬而未决的问题。
我知道的唯一可行的解决方法(我自己也测试过)是使用 browser.webRequest.onHeadersReceived
动态更改 CSP 响应 header ,幸运的是,Edge 对此提供了良好的支持。
注意:此代码改编自这篇精彩的文章,该文章也更详细地解释了该问题:https://transitory.technology/browser-extensions-and-csp-headers/
代码将您的扩展添加到每个 CSP header 和指令允许的 URL,它应该在后台页面中执行,并且应该设置为持久
。
确保将 webRequest
和 webRequestBlocking
权限添加到您的 manifest.json
。
const cspHeaderNames = [
'content-security-policy',
'content-security-policy-report-only',
'x-webkit-csp'
];
// @see https://developer.mozilla.org/en-US/docs/Web/Security/CSP/CSP_policy_directives
const cspSources = [
'connect-src',
'default-src',
'font-src',
'frame-src',
'img-src',
'media-src',
'object-src',
'script-src',
'style-src',
'child-src',
'form-action',
];
const url = browser.extension.getURL("").slice(0, -1); // (remove trailing "/")
browser.webRequest.onHeadersReceived.addListener(details => {
details.responseHeaders.forEach(header => {
const isCspHeader = cspHeaderNames.indexOf(header.name.toLowerCase()) >= 0;
if (isCspHeader) {
let newValue = header.value;
cspSources.forEach(source => {
newValue = newValue.replace(source, source + ' ' + url);
});
header.value = newValue;
}
});
return {
responseHeaders: details.responseHeaders
};
}, {
urls: ['<all_urls>'],
types: ['main_frame', "sub_frame"],
}, ["blocking", "responseHeaders"]);
关于javascript - 请求 JSON 的边缘扩展不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47326095/