当出现“内容安全策略”错误时,如何使用FireFox中的GreaseMonkey脚本播放声音?

时间:2015-02-17 03:09:11

标签: firefox greasemonkey content-security-policy

var audioPlayer = new Audio("http://URLTOMYSOUND/ping.mp3");
audioPlayer.play();

加载音频时出现此错误:

  

内容安全政策:网页设置阻止加载   资源......

我如何解决这个问题?我不在乎声音在哪里,我只是想玩它。它可能是本地的,但我的印象是本地文件访问也是禁忌。

1 个答案:

答案 0 :(得分:6)

如果您遇到Greasemonkey 2.3中的内容安全策略(CSP)问题,则无法(此时)从文件播放声音。如果您可以修改要运行的站点的HTTP标头,则可以。 请参阅Using Content Security PolicyCSP policy directives

使用“允许这些请求跨越相同的原始策略边界”的GM_xmlhttpRequest,由于当前GM 2.3中的错误而无效。 请参阅issue #2045 。问题源于无法将ArrayBuffer复制到沙箱中以获得正确的解码权限等。

下面的代码段应该适用于未来的GM版本。

// ==UserScript==
// @name        Testing Web Audio: Load from file
// @namespace   http://ericeastwood.com/
// @include     http://example.com/
// @version     1
// @grant       GM_xmlhttpRequest
// ==/UserScript==
window.AudioContext = window.AudioContext || window.webkitAudioContext;
var context = new AudioContext();
// Note: this is not an actual reference to a real mp3
var url = 'http://example.com/some.mp3';

var soundLoadedPromise = new Promise(function(resolve, reject) {
    // This will get around the CORS issue
    //      http://wiki.greasespot.net/GM_xmlhttpRequest
    var req = GM_xmlhttpRequest({
        method: "GET",
        url: url,
        responseType: 'arraybuffer',
        onload: function(response) {
            try {
                context.decodeAudioData(response.response, function(buffer) { 
                    resolve(buffer)
                }, function(e) {
                    reject(e);
                }); 
            }
            catch(e) {
                reject(e);
            }
        }
    });
});

soundLoadedPromise.then(function(buffer) {
    playSound(buffer);
}, function(e) {
    console.log(e);
});

function playSound(buffer) {
    // creates a sound source
    var source = context.createBufferSource();
    // tell the source which sound to play
    source.buffer = buffer;
    // connect the source to the context's destination (the speakers)
    source.connect(context.destination);
    // play the source now
    // note: on older systems, may have to use deprecated noteOn(time);
    source.start(0);
}

现在,如果你只需要一些声音,我会用振荡器在程序上生成它。以下演示使用AudioContext.createOscillator

演示:jsFiddle

// ==UserScript==
// @name        Test Web Audio: Oscillator - Web Audio
// @namespace   http://ericeastwood.com/
// @include     http://example.com/
// @version     1
// @grant       none
// ==/UserScript==
window.AudioContext = window.AudioContext || window.webkitAudioContext;

context = new AudioContext();

var o = context.createOscillator();
o.type = 'sine';
o.frequency.value = 261.63;
o.connect(context.destination);

// Start the sound
o.start(0);
// Play the sound for a second before stopping it
setTimeout(function() {
    o.stop(0);
}, 1000);