如何在没有jquery的情况下将脚本注入文档<head>

noo*_*der 0 html javascript jquery dom google-chrome-extension

我正在构建一个浏览器扩展,并且在<script>标签内部有一个函数,该函数可以修改需要注入<head>任何给定网页的DOM 。整个函数是一个string("<script>function content blah blah</script>")。我正在使用jQuery来实现这一点:

$('head').prepend(modFunction);
Run Code Online (Sandbox Code Playgroud)

而且效果很好。我出于某些原因希望删除jQuery,但是当我尝试创建一个<script>元素注入普通<head>javascript时,一切都会失败。到目前为止,我已经尝试了两种方法:

1。

  var headSelector = document.querySelector('head');
  var el = document.createElement('div');
  el.innerHTML = modFunction;
  modFunction = el.firstChild;
  headSelector.insertBefore(modFunction, headSelector.firstChild);
Run Code Online (Sandbox Code Playgroud)

2。document.head.insertAdjacentHTML('afterbegin', modFunction);

两种javascript尝试都将<script>具有正确功能的标记插入<head>,但是均未执行该功能。不知道为什么jQuery可以正常工作,而普通的javascript无法正常工作。任何帮助将不胜感激。谢谢

小智 5

你有一些错误。

  1. 如果你modFunction是一个包含字符串,<script>其前后标签,你的代码将无法正常工作,因为改变innerHTMLdiv将不执行添加脚本。

  2. insertAdjacentHTML不需要使用function,因为modFunction现在是type的对象Text,它将[object Text]在脚本之前插入字符串。

  3. 而是使用appendChild函数将正确的新脚本元素插入head。

尽管@ Jantho1990表示最好从文件中加载脚本,但是许多浏览器都使用缓存,因此,如果您更改脚本源,则它在浏览器中将始终不可见。

var scriptSource = '//YourScriptSource.....';
var scriptElem = document.createElement('script');
scriptElem.text = scriptSource;
document.head.appendChild(scriptElem);
Run Code Online (Sandbox Code Playgroud)