gpt4 book ai didi

firefox-addon - 如何将内容安全策略添加到 Firefox 扩展

转载 作者:行者123 更新时间:2023-12-02 04:48:51 26 4
gpt4 key购买 nike

我有一个插件,我必须在 Chrome 和 Firefox 浏览器上都支持它。该插件执行跨脚本加载。

在 Chrome 中,通过在我的 manifest.json 文件中添加内容安全策略,我可以摆脱它。我该怎么做 Firefox 扩展?

最佳答案

我无法为我的问题找到一个简单的解决方案,在查找一些 firefox 插件扩展后,我不得不想出我自己的解决方案,如下所示。下面的解决方案在 FF 24.0 上进行了测试,但也应该适用于其他版本。

Cc["@mozilla.org/observer-service;1"].getService(Ci.nsIObserverService)
.addObserver(_httpExamineCallback, "http-on-examine-response", false);

function _httpExamineCallback(aSubject, aTopic, aData) {
var httpChannel = aSubject.QueryInterface(Ci.nsIHttpChannel);

if (httpChannel.responseStatus !== 200) {
return;
}

var cspRules;
var mycsp;
// thre is no clean way to check the presence of csp header. an exception
// will be thrown if it is not there.
// https://developer.mozilla.org/en-US/docs/XPCOM_Interface_Reference/nsIHttpChannel
try {
cspRules = httpChannel.getResponseHeader("Content-Security-Policy");
mycsp = _getCspAppendingMyHostDirective(cspRules);
httpChannel.setResponseHeader('Content-Security-Policy', mycsp, false);
} catch (e) {
try {
// Fallback mechanism support
cspRules = httpChannel.getResponseHeader("X-Content-Security-Policy");
mycsp = _getCspAppendingMyHostDirective(cspRules);
httpChannel.setResponseHeader('X-Content-Security-Policy', mycsp, false);
} catch (e) {
// no csp headers defined
return;
}
}

};

/**
* @var cspRules : content security policy
* For my requirement i have to append rule just to 'script-src' directive. But you can
* modify this function to your need.
*
*/
function _getCspAppendingMyHostDirective(cspRules) {
var rules = cspRules.split(';'),
scriptSrcDefined = false,
defaultSrcIndex = -1;

for (var ii = 0; ii < rules.length; ii++) {
if ( rules[ii].toLowerCase().indexOf('script-src') != -1 ) {
rules[ii] = rules[ii] + ' <My CSP Rule gets appended here>';
scriptSrcDefined = true;
}

if (rules[ii].toLowerCase().indexOf('default-src') != -1) {
defaultSrcIndex = ii;
}
}

// few publishers will put every thing in the default (default-src) directive,
// without defining script-src. We need to modify those as well.
if ((!scriptSrcDefined) && (defaultSrcIndex != -1)) {
rules[defaultSrcIndex] = rules[defaultSrcIndex] + ' <My CSP rule gets appended here>';
}

return rules.join(';');
};

关于firefox-addon - 如何将内容安全策略添加到 Firefox 扩展,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19264831/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com