1

If my script having a param, how can we read the id param inside the javascript script <script src="https://test.com/test.js?id=123"></script> I have tried getting the base html URL from window.location but i am looking for reading params from js url

2 Answers2

2

You can do this as follows:

const scriptTag = document.getElementById('my-script-tag');
const scriptUrl = scriptTag.getAttribute('src');
alert(scriptUrl);
<script id="my-script-tag" src="https://some.js.url?some=parameter">
</script>
Titulum
  • 9,928
  • 11
  • 41
  • 79
  • 1
    I would like to know any usage of this stuff. When I have the script tag in my file, why should I parse my own file instead of using the values which I already know? – Thallius Jul 28 '21 at 07:29
  • I don't really know what the usecase of this is, I just answered the question :) – Titulum Jul 28 '21 at 07:32
  • Usage can be somewhere where the same js is used in multiple places. Instead of hosting the multiple js with the hardcoded value. – Vaibhav Seth Jul 28 '21 at 07:34
  • You cannot insert the same script two times. If you insert the script it is available from all other sources – Thallius Jul 28 '21 at 10:59
1

You can use document.currentScript and an URL object to parse it for you.

<script src="https://test.com/test.js?id=123">
  const curScriptElement = document.currentScript;
  const url = new URL(curScriptElement.src);
  const params = url.searchParams;
  const id = params.get('id')
</script>
pilchard
  • 12,414
  • 5
  • 11
  • 23