我正在使用 midi.js 构建 Chrome 扩展程序插入。 该插件内的函数之一将脚本返回到 DOM,我不知道如何直接注入(inject)该脚本,但我必须这样做,因为这是一种安全违规。
这就是函数 -
var addSoundfont = function(text) {
var script = document.createElement("script");
script.language = "javascript";
script.type = "text/javascript";
script.text = text;
document.body.appendChild(script);
};
这就是它的名字 -
connect.webaudio = function(filetype, instruments, conf) {
if (MIDI.loader) MIDI.loader.message("Web Audio API...");
// works awesome! safari, chrome and firefox support.
var queue = createQueue({
items: instruments,
getNext: function(instrumentId) {
DOMLoader.sendRequest({
url: MIDI.soundfontUrl + instrumentId + "-" + filetype + ".js",
onprogress: getPercent,
onload: function(response) {
addSoundfont(response.responseText);
if (MIDI.loader) MIDI.loader.update(null, "Downloading...", 100);
queue.getNext();
}
});
},
onComplete: function() {
MIDI.WebAudio.connect(conf);
}
});
};
这是我复制到函数中的返回脚本,注入(inject)的脚本创建了一个对象,该对象将调用链接到在线声音文件(声音字体)。它可以工作,但不如 Xan 的解决方案那么优雅:
if (typeof(MIDI.Soundfont) === "undefined") MIDI.Soundfont = {};
MIDI.Soundfont.acoustic_grand_piano = {
"A0": "data:audio/ogg;base64,T2dn.......
然后它就永远持续下去..
感谢您的阅读!
最佳答案
您可以只注入(inject) <script src="">
,而不是加载脚本然后插入其内嵌文本。使用适当的 URL 标记。
getNext: function(instrumentId) {
// Assuming MIDI.soundfontUrl in in "chrome-extension://" origin
// Also, see chrome.runtime.getURL()
var url = MIDI.soundfontUrl + instrumentId + "-" + filetype + ".js";
var el = document.createElement("script");
el.src = url;
// This is synchronous:
document.body.appendChild(el);
queue.getNext();
}
这假设 js 文件是用扩展名打包的。如果不是:
原点必须是
https://
您需要将源添加到自定义 CSP:Remote Script
关于javascript - 构建 Chrome 扩展程序时如何摆脱插件内的内联代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27619780/