1

I have

    <script type="text/javascript" src="./js/rendering.js?id=3"> 

I want to get id value in my rendering.js how can I achieve this?

Vengat
  • 119
  • 1
  • 9
  • 1
    Does this answer your question? [Passing parameters to JavaScript files](https://stackoverflow.com/questions/2190801/passing-parameters-to-javascript-files) – Cid Aug 17 '20 at 11:41
  • @Cid it can work but the user only copy-paste generated script similar to above, I need to read the user id from only external js. the generated script tag should be in the above format may be with some single line changes – Vengat Aug 17 '20 at 11:49

1 Answers1

1

To get the URL of the current JavaScript file you can use the fact that it will be the last <script> element currently on the page.

var scripts = document.getElementsByTagName('script');
var script = scripts[scripts.length - 1];
var scriptURL = script.src;

Please note that this code will only work if it executes directly within the JS file, i.e. not inside a document-ready callback or anything else that's called asynchronously. Then you can use any "get querystring parameter" JS (but make sure to replace any location.search references in there) to extract the argument.

I'd suggest you to put the value in a data-id argument though - that way you can simply use e.g. script.getAttribute('data-id') to get the value.

Jay
  • 2,826
  • 2
  • 13
  • 28
  • :) Thanks, it worked to get the URL after that I just followed https://gomakethings.com/getting-all-query-string-values-from-a-url-with-vanilla-js/ this page to achieve my requirement – Vengat Aug 17 '20 at 11:59