问题
I'm developing a small chrome extension for myself to embed an iframe into the website. Content Security Policy makes this difficult, since the frame-src directive on a few websites doesn't allow my content to be loaded. The error message is the following:
Refused to frame 'mydomain' because it violates the following Content Security Policy directive: "frame-src someotherdomain".
So far, I have tried adding my host to the frame-src directive and to the frame-ancestors in webRequest.onHeadersReceived.
Permissions in the manifest.json
are the following:
"permissions": ["contextMenus", "webRequest", "<all_urls>", "tabs", "webRequestBlocking"],
Editing the headers in the background.js
:
chrome.webRequest.onHeadersReceived.addListener(
editCSPHeader,
{
urls: [ "<all_urls>" ],
types: [ "sub_frame" ]
},
["blocking", "responseHeaders"]
);
function editCSPHeader(r) {
const headers = r.responseHeaders; // original headers
for (let i=headers.length-1; i>=0; --i) {
let header = headers[i].name.toLowerCase();
if (header === "content-security-policy") {
headers[i].value = headers[i].value.replace("frame-src", "frame-src https://*.mydomain.xy/*");
}
}
return {responseHeaders: headers};
}
After the iframe still not being loaded properly, I did a capture using chrome://net-export. Here the headers showed up as unmodified, even though they should be edited.
回答1:
The sources from which you can load iframes are restricted by the CSP of their parent frame.
If you want to embed your iframe into the main frame, you need to change the CSP header in the main frame. Change types: [ "sub_frame" ]
in your code above to types: [ "main_frame" ]
to do that.
Also please note that manipulation of headers using chrome.webRequest.onHeadersReceived
is not very reliable. Only one extension at a time can modify them, so other extensions that do so may break your extension.
来源:https://stackoverflow.com/questions/57133872/edit-content-security-policy-in-onheadersreceived