|
// Attempts to retrieve the absolute path of the executing script. |
|
// Pass a function as 'callback' which will be executed once the |
|
// URL is known, with the first argument being the string URL. |
|
function getScriptName(ex, callback) { |
|
if (typeof ex == 'function') { |
|
try { |
|
(0)(); |
|
} catch(e) { |
|
getScriptName(e, ex); |
|
} |
|
} else { |
|
|
|
// Getting the URL of the exception is non-standard, and |
|
// different in EVERY browser unfortunately. |
|
|
|
if (ex['fileName']) { // Firefox |
|
//console.log("firefox"); |
|
callback(ex['fileName']); |
|
|
|
} else if (ex['sourceURL']) { // Safari |
|
//console.log("safari"); |
|
callback(ex['sourceURL']); |
|
|
|
} else if (ex['arguments']) { // V8 (Chrome) |
|
//console.log("chrome"); |
|
var originalPrepareStackTrace = Error['prepareStackTrace']; |
|
Error['prepareStackTrace'] = function(error, structuredStackTrace) { |
|
return structuredStackTrace[1].getFileName(); |
|
} |
|
// When Error#stack is 'get', Error.prepareStackTrace is |
|
// called and what's returned is the stack value. See: |
|
// http://code.google.com/p/v8/wiki/JavaScriptStackTraceApi |
|
var stack = ex['stack']; |
|
Error['prepareStackTrace'] = originalPrepareStackTrace; |
|
callback(stack); |
|
|
|
} else if (ex['stack']) { // Opera 10 |
|
//console.log("opera"); |
|
var s = ex['stack']; |
|
s = s.split("\n")[0]; |
|
s = s.substring(s.indexOf("@")+1); |
|
callback(s.substring(0, s.lastIndexOf(":"))); |
|
|
|
} else { // Internet Explorer 8+ |
|
//console.log("internet explorer"); |
|
var origOnError = window['onerror']; |
|
window['onerror'] = function(msg, url){ |
|
window['onerror'] = origOnError; |
|
// 'callback' gets invoked in IE 6 & 7, but the |
|
// 'url' is incorrectly set to location.href. |
|
// It seems impossible to do correctly this in IE <= 7. See: |
|
// http://stackoverflow.com/questions/3019112/getting-url-of-executing-javascript-file-ie6-7-problem-mostly |
|
callback(url); |
|
return true; |
|
} |
|
throw ex; |
|
} |
|
} |
|
} |
|
|
|
|
|
getScriptName(function(name) { |
|
document.write("<i>"+name+"</i><br>"); |
|
var correctName = "getScriptName.js"; |
|
var isCorrect = name.lastIndexOf(correctName) === name.length - correctName.length; |
|
document.write("URL ends with '"+correctName+"': <b>"+isCorrect+"</b><br><br>"); |
|
}); |