<script src="http://localhost:3000/test.js?addr=(address)"> </script
每个实例的地址都不同 我尝试了What is my script src URL?和JavaScript - How do I get the URL of script being called?的答案,但他们总是给出相同的来源。以下是
的示例输出 var scripts = document.getElementsByTagName('script'),
script = scripts[scripts.length - 1];
console.log (script.getAttribute('src', -1))
如何获得实际来源?
答案 0 :(得分:2)
如果我理解清楚,你想要的是document.currentScript
,它将返回正在被解析的脚本元素(注意,首次执行脚本后它将为null,因此你可能想要进行你的url解析同步):
<script id="find_me">
// replace 'id' with 'src' for your case
console.log(document.currentScript.id);
</script>
<script id="me_too">
console.log(document.currentScript.id);
</script>
<script id="and_even_from_remote" src="data:application/javascript,console.log(document.currentScript.id)"></script>
&#13;