Skip to content

Instantly share code, notes, and snippets.

@LiuJi-Jim
Created November 20, 2015 07:58
Show Gist options
  • Save LiuJi-Jim/53a7cd5c0b65616239e2 to your computer and use it in GitHub Desktop.
Save LiuJi-Jim/53a7cd5c0b65616239e2 to your computer and use it in GitHub Desktop.
getCurrentScript
var getCurrentScript = (function () {
var supportsScriptReadyState = ('readyState' in document.createElement('script'))
var isNotOpera = !window.opera || window.opera.toString() !== "[object Opera]"
function getCurrentScript() {
if (document.currentScript) {
// Chrome, OSX Safari, Firefox, Edge
return document.currentScript.src
}
if (supportsScriptReadyState && isNotOpera) {
// IE 6, 7, 8, 9, 10
var scripts = document.getElementsByTagName('script')
var i = scripts.length
while (i--) {
var tag = scripts[i]
if (tag.readyState === 'interactive') {
return tag.src
}
}
}
// IE11, windows Safari
var stack
try {
a.b.c() // 强制报错,以便捕获e.stack
} catch (e) {
// windows safari的错误对象只有line,sourceId,sourceURL
if (typeof e.sourceURL === 'string') {
return e.sourceURL
}
stack = e.stack
if (!stack && window.opera) {
//opera 9没有e.stack,但有e.Backtrace,但不能直接取得,需要对e对象转字符串进行抽取
stack = (String(e).match(/of linked script \S+/g) || []).join(" ")
}
}
if (stack) {
/**
* e.stack最后一行在所有支持的浏览器大致如下:
*chrome23:
* at http://113.93.50.63/data.js:4:1
*firefox17:
*@http://113.93.50.63/query.js:4
*opera12:
*@http://113.93.50.63/data.js:4
*IE10:
* at Global code (http://113.93.50.63/data.js:4:1)
*/
stack = stack.split(/[@ ]/g).pop() // 取得最后一行,最后一个空格或@之后的部分
stack = stack[0] == "(" ? stack.slice(1, -1) : stack
return stack.replace(/(:\d+)?:\d+$/i, "") // 去掉行号与或许存在的出错字符起始位置
}
}
return getCurrentScript
})()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment