Get query string in named javascript file

Is it possible to get request parameters with javascript in the named javascript file as follows:

// in html <script src="/file.js?query=string"></script> // in file.js console.log(this.location.query) 

Is this possible somehow, or should I use a server?

+6
source share
6 answers

No, this is not possible because the script file has no view in the global javascript scope. You can only find its element inside the DOM, as shown by haitaka, but this is a very non-standard and, of course, not recommended way to pass script parameters.

+5
source

You can add the id attribute to the script tag as follows:

 <script src="/file.js?query=string" id="query"></script> 

and then name it:

 console.log(document.getElementById("query").src.split("query=")[1]); 

Below is a small working code example:

 <html> <head> <script src="aaa.js?query=abcd" id="query"></script> </head> <body></body> </html> 

Here is the code inside aaa.js:

 window.onload=function(){ alert(document.getElementById("query").src.split("query=")[1]); } 
+8
source

I could get src with the code below. So I think you can parse the queryString.

 document.currentScript.src 
+3
source

I know this is old, but I thought I would drop my two cents ...

If you already add id to the script element, why not add a custom attribute:

 <script src="/file.js" id="query" value="string"></script> 

Then you can get the value using getAttribute:

 document.getElementById('query').getAttribute('value'); 
0
source

I know this is old, but I thought you did not mind (one more) two more cents ...

If you do NOT add id to the script element, James Smith has a fragment that does not require the id attribute . And this id-less characteristic is huge because your script file does NOT need to bind to the id on the caller side.

 // Extract "GET" parameters from a JS include querystring function getParams(script_name) { // Find all script tags var scripts = document.getElementsByTagName("script"); // Look through them trying to find ourselves for(var i=0; i<scripts.length; i++) { if(scripts[i].src.indexOf("/" + script_name) > -1) { // Get an array of key=value strings of params var pa = scripts[i].src.split("?").pop().split("&"); // Split each key=value into array, the construct js object var p = {}; for(var j=0; j<pa.length; j++) { var kv = pa[j].split("="); p[kv[0]] = kv[1]; } return p; } } // No scripts match return {}; } 
0
source

Try this to get the request value using javascript

 alert(window.location.href.split["?"][1].split["="][1]); 
-3
source

All Articles