javascript - 构建 Chrome 扩展程序时如何摆脱插件内的内联代码

标签 javascript google-chrome google-chrome-extension

我正在使用 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 文件是用扩展名打包的。如果不是:

  1. 原点必须是 https://

  2. 您需要将源添加到自定义 CSP:Remote Script

关于javascript - 构建 Chrome 扩展程序时如何摆脱插件内的内联代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27619780/

相关文章:

javascript - 流式 Web 应用程序 - Twitter、Facebook、NoSQL 还是 SQL?

css - Chrome的手机模拟器和iPhone模拟器有高度差吗?

javascript - &lt;input type="date> onchange 触发太多

google-chrome - 哪个 IDE 最适合扩展开发?

javascript - 在javascript中下载canvas时出现"Not allowed to navigate top frame to data URL"

javascript - 无法在 electron.js 应用程序的 main.js 文件中加载 node.js 模块

javascript - ecmascript 正则表达式查找/替换 Chrome 主页

javascript - jQuery 在 Chrome 扩展中未定义?

Javascript/jQuery 浏览器检测

javascript - meteor 应用程序 : how to get a unique session/client id without using accounts