I am building a browser extension and I have a function inside of <script>
tags that modifies the DOM that I need to inject into the <head>
of any given webpage. The entire function is a string("<script>function content blah blah</script>"
). I was using jquery to achieve this:
$('head').prepend(modFunction);
and this works fine. I would like to remove jQuery for a few reasons but when I try to create a <script>
element to inject into the <head>
with vanilla javascript everything fails. I have tried two methods so far:
1.
var headSelector = document.querySelector('head');
var el = document.createElement('div');
el.innerHTML = modFunction;
modFunction = el.firstChild;
headSelector.insertBefore(modFunction, headSelector.firstChild);
2.document.head.insertAdjacentHTML('afterbegin', modFunction);
Both javascript attempts inject a <script>
tag with the correct function into the <head>
, however, neither executes the function. Not sure why jQuery is working and the vanilla javascript doesn't. Any help would be greatly appreciated. Thanks