Skip to content

Instantly share code, notes, and snippets.

@seleb
Created February 8, 2018 05:33
Show Gist options
  • Save seleb/27798c1022e14aba82b9b77b97ad8002 to your computer and use it in GitHub Desktop.
Save seleb/27798c1022e14aba82b9b77b97ad8002 to your computer and use it in GitHub Desktop.
inject code into script tags based on a search string
// helper used to inject code into script tags based on a search string
var inject = function (searchString, codeToInject) {
// find the relevant script tag
var scriptTags = document.getElementsByTagName('script');
var scriptTag;
var code;
for (var i = 0; i < scriptTags.length; ++i) {
scriptTag = scriptTags[i];
if (
scriptTag.textContent.indexOf(searchString) >= 0 // script contains the search string
&&
scriptTag != document.currentScript // script isn't the one doing the injecting (which also contains the search string)
) {
code = scriptTag.textContent;
break;
}
}
// error-handling
if (!code) {
throw 'Couldn\'t find "' + searchString + '" in script tags';
}
// modify the content
code = code.replace(searchString, searchString + codeToInject);
// replace the old script tag with a new one using our modified code
scriptTag.remove();
scriptTag = document.createElement('script');
scriptTag.textContent = code;
document.head.appendChild(scriptTag);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment