【问题标题】:Trouble adding third party libraries to chrome extension无法将第三方库添加到 chrome 扩展
【发布时间】:2019-12-21 02:29:31
【问题描述】:

问题

我正在尝试将第三方库添加到我正在构建的 chrome 扩展中。我正在尝试动态添加脚本。我下载了 jquery 并将其添加到项目中。然后我尝试使用 jquery 动态添加 p5.min.js 和 p5.dom.min.js。

  • 出现错误。

Image of error message -- p5.dom.min.js 加载了,p5.min.js 没有加载?

代码

  • 在 manifest.json 中:

    "js": [
                     "jquery-3.2.1.min.js", "content2.js"
                ],
    
  • 在 content2.js 中:

    var script1 = document.createElement('script');
    script1.src = 'jquery-3.2.1.min.js';
    document.getElementsByTagName('head')[0].appendChild(script1);
    
    $('head').append("<script type='text/javascript' src='https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.7.3/p5.min.js'>");
    $('head').append("<script type='text/javascript' src='https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.7.3/addons/p5.dom.min.js'>");
    
    var s = function(sketch){
      //lotsa code.
    }
    
    
    var myp5 = new p5(s);
    

注意事项

【问题讨论】:

  • 我对 Chrome 扩展一无所知,但我想知道在 head 部分附加 &lt;script&gt; 标记是否真的会加载该 JavaScript 文件?
  • 内容脚本在“孤立的世界”中运行,但 DOM 脚本元素在页面上下文中运行,因此它们彼此看不到。您的第一个注释描述了正确的方法,因此这是您应该做的。那里究竟是什么“不起作用”?编辑此问题或使用MCVE 打开一个新问题。

标签: javascript google-chrome-extension p5.js


【解决方案1】:

你不需要 jquery。你呢……

 script1.type='text/javascript';

您可能还想考虑...

 script1.async=true;

对于即时测试,您还可以包括...

 script1.onload=function(){alert('Script loaded!');};

【讨论】:

  • 真正的问题是内容脚本在“孤立的世界”中运行,但 DOM 脚本元素在页面上下文中运行,因此它们无法看到彼此。
猜你喜欢
  • 2014-01-07
  • 2018-01-12
  • 2017-12-09
  • 2014-10-21
  • 2018-04-25
  • 2018-06-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多