Created
June 3, 2019 05:57
-
-
Save JoshBarr/0ad909205f44c974f76f20abbbd8bea7 to your computer and use it in GitHub Desktop.
Guess current script
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
/* | |
Attempt to guess which <script src=""> tag loaded the current file. | |
If the file was loaded as a chunk by Webpack, try and find the webpack root. | |
*/ | |
function guessCurrentScript() { | |
var err = new Error(); | |
Error.stackTraceLimit = 100; | |
var stack = err.stack; | |
var getAnchor = function(href) { | |
var l = document.createElement("a"); | |
l.href = href; | |
return l; | |
}; | |
var needle; | |
var regex = new RegExp("(http.+):[0-9]+:[0-9]+$",'i'); | |
var webpackModuleRegex = new RegExp("webpackJsonpCallback.+((http.+):[0-9]+:[0-9]+)", 'i'); | |
var matches = stack.match(regex); | |
var webpackMatches = stack.match(webpackModuleRegex); | |
var scriptSrc = webpackMatches.length ? webpackMatches[2] : matches[1]; | |
var path = getAnchor(scriptSrc).pathname; | |
for (var i = 0; i < document.scripts.length; i++) { | |
var script = document.scripts[i]; | |
if (script.src === scriptSrc || script.src === path) { | |
needle = script; | |
} | |
} | |
return needle; | |
} | |
console.log('currentScript', guessCurrentScript()); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment