Created
February 8, 2018 05:33
-
-
Save seleb/27798c1022e14aba82b9b77b97ad8002 to your computer and use it in GitHub Desktop.
inject code into script tags based on a search string
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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