1
<script src="http://localhost:3000/test.js?addr=(address)"> </script

The address is different for each instance I tried the answers from What is my script src URL? and JavaScript - How do I get the URL of script being called? but they always give the same source. Here is an example output from

var scripts = document.getElementsByTagName('script'), script = scripts[scripts.length - 1]; console.log (script.getAttribute('src', -1))

enter image description here

How can I get the actual source?

Joe
  • 321
  • 1
  • 2
  • 12

1 Answers1

2

If I understand clearly, what you want is document.currentScript which will return the script element which is being parsed (beware, it will be null after first execution of the script, so you might want to do your url parsing synchronously) :

<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>
Kaiido
  • 123,334
  • 13
  • 219
  • 285
  • I'm not sure what you mean by the warning, I get null every time – Joe Jun 14 '17 at 12:08
  • @Joe, even in the snippet ? By the warning I mean you need to get it from when the script is being processed the first time, like I do here. If you call it again in an asynchronous function (e.g in a setTimeout, or in an Event, be it `window.onload`) then it will return null. But actually, with the same restrictions, `var s = document.querySelectorAll('script'); var yourScript = s[s.length - 1]` should do the same, since no other element would have been parsed since then. – Kaiido Jun 14 '17 at 12:12
  • I meant when I copied the code into mine I get null – Joe Jun 14 '17 at 12:22
  • @joe and when are calling it ? If it is in an event, like window.onload, or jquery equivalent, then it won't work. – Kaiido Jun 14 '17 at 12:25
  • It should run as soon as it is created. The script loads jquery first so it may be that is causing issues – Joe Jun 14 '17 at 12:39