在onHeaders中编辑内容安全策略 [英] Edit Content Security Policy in onHeadersReceived

查看:56
本文介绍了在onHeaders中编辑内容安全策略的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为自己开发一个小的chrome扩展程序,以便将iframe嵌入到网站中.内容安全策略使此工作变得很困难,因为一些网站上的frame-src指令不允许加载我的内容.错误消息如下:

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:

拒绝使用框架"mydomain",因为它违反了以下内容安全策略指令:"frame-src someotherdomain".

Refused to frame 'mydomain' because it violates the following Content Security Policy directive: "frame-src someotherdomain".

到目前为止,我已经尝试将主机添加到frame-src指令以及webRequest.onHeadersReceived中的帧祖先.

So far, I have tried adding my host to the frame-src directive and to the frame-ancestors in webRequest.onHeadersReceived.

manifest.json 中的权限如下:

Permissions in the manifest.json are the following:

    "permissions": ["contextMenus", "webRequest", "<all_urls>", "tabs", "webRequestBlocking"],

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};
}

在iframe仍然无法正确加载之后,我使用chrome://net-export进行了捕获.在这里,标题显示为未经修改,即使应该对其进行编辑.

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.

推荐答案

可以从其加载iframe的源受其父框架的CSP限制.

如果要将iframe嵌入到主框架中,则需要更改主框架中的CSP标头.将上面代码中的 types:["sub_frame"] 更改为 types:["main_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.

还请注意,使用 chrome.webRequest.onHeadersReceived 操作标头不是很可靠.一次只能修改一个扩展名,因此其他扩展名可能会破坏您的扩展名.

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.

这篇关于在onHeaders中编辑内容安全策略的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆