As an example, I have the following html:
<body> <script src="code.js?q=xyz"></script> </body>
I want to be able to read the
q=xyz query parameter from within
code.js. I tried:
But it gives me the html document's URL, not
code.js's URL (I could then parse the URL for the query parameters).
You could use
document.currentScript.src to access the
src-attribute and then extract the query parameter. For older browsers (such as IE 11) access the
var scripts = document.getElementsByTagName('script'); var src = scripts[scripts.length - 1].src;
This will return the
src-attribute of the last executed script.
In some cases the last executed script is not the current script (for example, if a script manipulates other
<script>-elements), and therefore it's a bit unreliable.
©2020 All rights reserved.