比如当前网页是http://www.aaa.com/里面有代码
<script src="http://www.BBB.com/test.js"></script>
test.js运行的时候能知道自己的URL吗, 此时test.js的location.href是http://www.aaa.com/我想获得http://www.BBB.com/test.js的
<script src="http://www.BBB.com/test.js"></script>
test.js运行的时候能知道自己的URL吗, 此时test.js的location.href是http://www.aaa.com/我想获得http://www.BBB.com/test.js的
(function(){
try {
throw Error("获取路径")
}catch(ex){
if(ex.fileName)//Firefox
strJsPath=ex.fileName
else if(ex.stack)//Chrome
strJsPath=(ex.stack.match(/at\s+(.*?):\d+:\d+/)||['',''])[1];
else if(ex.sourceURL)//Safari
strJsPath=ex.sourceURL
}
if(strJsPath)return; //其实所有浏览器都可以用下面的
var scripts=document.getElementsByTagName("script"),script=scripts[scripts.length-1];
strJsPath=document.querySelector?script.src:script.getAttribute("src",4)//IE8直接.src
})()
alert(strJsPath)
strJsPath=script.getAttribute("src");