Edit Content Security Policy in onHeadersReceived

假如想象 提交于 2021-01-28 06:37:29

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!