Get js file query param from inside

I load this file with some query parameter as follows:
src='somefile.js?userId=123'

I wrote the following function in somefile.js file that reads userId request parameter
but I think this is not the best approach. Honestly, this is pretty ugly. Is there a better way ?

 function getId(){ var scripts = document.getElementsByTagName('script'), script; for(var i in scripts){ if( scripts.hasOwnProperty(i) && scripts[i].src.indexOf('somefile.js') != -1 ) var script = scripts[i]; } var s = (script.getAttribute.length !== undefined) ? script.getAttribute('src') : script.getAttribute('src', 2); return getQueryParams('userId',s); }; 
+4
source share
4 answers
 // extracts the params from the currently running (external) script var getScriptQp = (function(){ var scripts = document.getElementsByTagName('script'); var this_script_tag = scripts[scripts.length - 1]; //script tag of this file if( typeof this_script_tag != undefined && this_script_tag.src ) var s = this_script_tag.src; else{ return this.customer; } return s; })(); // gets the Query Params of a givver query string function getQueryParam(name, query){ name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]"); var regexS = "[\\?&]" + name + "=([^&#]*)"; var regex = new RegExp(regexS); var results = regex.exec(query); if (results == null) return ""; else return results[1]; } getQueryParam( 'param',getScriptQp ); 
+2
source

Reading script elements in the head section is the way to go. There is an article with sample code. This approach seems fragile, as the script name is hard-coded, and if it is renamed, it may break.

+1
source

Alternative methods:

  • Just set the JS variable with this value. For instance. <script>var userId = 123;</script> .
  • Put the value in a hidden element (element) somewhere in the HTML DOM and access it in the usual way.

However, keep in mind that JS code runs on the client side and is fully controlled by the client. For example, you really shouldn't let JS execute some user logic that depends on userId. In that case, rather save the userId in a server-side session and use ajax to get the result.

+1
source

Someone will correct me if I am mistaken, but I am sure that if you pass your parameters through the URL of your script, this means that the client will never cache your JS file, because each time it appears as a different URL and will be reloaded.

0
source

All Articles