1

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.

  • You can embed an iframe that points to your own extension html page (listed in [web_accessible_resources](https://developer.chrome.com/extensions/manifest/web_accessible_resources) of course), where you can embed an iframe with that other site. No need for webRequest's fragile header manipulation that fails when other extensions modify the headers. – wOxxOm Jul 21 '19 at 14:17
  • 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. – Petr Srníček Jul 21 '19 at 15:13
  • Changing the type from `sub_frame` to `main_frame` indeed solved this issue. – solarisISBC Jul 21 '19 at 15:32
  • Since my comment seems to have solved the issue, I am posting it as an answer as suggested [here](https://meta.stackoverflow.com/questions/294791/what-if-i-answer-a-question-in-a-comment). – Petr Srníček Jul 22 '19 at 15:28

1 Answers1

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.

Petr Srníček
  • 2,296
  • 10
  • 22