2

I have a plugin which I have to support both on Chrome and Firefox browsers. The plugin does cross script loading.

In Chrome, by adding the content security policy in my manifest.json file, I could get away with it. How can I do it Firefox extension?

4

2 回答 2

5

我找不到一个简单的解决方案来解决我的问题,在查找一些 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(';');
};
于 2013-11-11T22:58:33.923 回答
0

未来计划在 SDK 中本地添加内容策略(错误 852297),但有一个第 3 方模块可以让您接近您想要的位置:policy.js

于 2013-10-09T20:26:19.560 回答