`document.currentScript` equivalent via a thrown Error's stack
by James Greene
HTML
<table border="1">
<tr>
<th>Type</th>
<th>Original</th>
<th>URL</th>
</tr>
</table>
CSS
td, th {
padding: 0px 5px;
}
JavaScript
(function () {
function append(type, original, url) {
$("table").append(
$("<tr></tr>").append(
$("<td></td>").text(type),
$("<td></td>").append($("<pre></pre>").text(original || "undefined")),
$("<td></td>").text(url)));
}
function getScriptURL(stack) {
var url;
if (typeof stack === "string" && stack) {
var matches = stack.match(/^(?:|[^:@]*@|.+\)@(?=http[s]?|file)|.+?\s+(?: at |@)(?:[^:\(]+ )*[\(]?)((?:http[s]?|file):\/\/[\/]?.+?\/[^:\)]*?)(?::\d+)(?::\d+)?/);
if (matches && matches[1]) {
url = matches[1];
} else {
matches = stack.match(/\)@((?:http[s]?|file):\/\/[\/]?.+?\/[^:\)]*?)(?::\d+)(?::\d+)?/);
if (matches && matches[1]) {
url = matches[1];
}
}
}
return url;
}
var scriptOnPageStacks = [
// Chrome
"Error: my uncaught error\n at http://jsfiddle.net/JamesMGreene/t5dzL/show/:139:7\n at jQuery.event.dispatch (http://code.jquery.com/blah.js:123:0)\n at foo",
// Safari 6.1
"http://jsfiddle.net/JamesMGreene/t5dzL/show/:139:7\ndispatch@http://code.jquery.com/blah.js:123:12\nfoo",
// PhantomJS
"Error: my error\n at http://jsfiddle.net/JamesMGreene/t5dzL/show/:139\n at http://code.jquery.com/blah.js:123\nfoo",
// Opera
"<anonymous function>([arguments not available])@http://jsfiddle.net/JamesMGreene/t5dzL/show/:139\n<anonymous function: dispatch>([arguments not available])@http://code.jquery.com/blah.js:123\nfoo",
// Safari 6.0
"@http://jsfiddle.net/JamesMGreene/t5dzL/show/:139\ndispatch@http://code.jquery.com/blah.js:123\nfoo",
// Win7 FF 3.6
"Error(\"my error\")@:0\u000a([object Object])@http://jsfiddle.net/JamesMGreene/t5dzL/show/:129\u000a([object Object])@http://code.jquery.com/blah.js:123\u000afoo",
// IE 10.0
"Error: my error\n at Anonymous function...