I have an external JavaScript file and I'd like to know the src attribute value URL that was used to include it in the tag from the HTML document. For example:
<script src='https://foo.bar/baz.js'><script>
And then inside baz.js I'd like to write this code:
let mysrc = getMySrc() // Should return https://foo.bar/baz.js
Is it possible to write a getMySrc() function that does this?
Use:
const src = document.currentScript.getAttribute('src');
This works because document.currentScript
will refer to the script tag corresponding to the currently running script.