Get the query string on the called javascript file

Is it possible to get the query parameters with javascript on the called javascript file like this:

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

// in file.js
console.log(this.location.query)

Is this possible somehow, or I have to use the server?


Solution 1:

You may append id attribute to script tag like this:

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

and then call it:

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

A small working sample code is below:

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

Here is the code inside of aaa.js:

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

Solution 2:

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

document.currentScript.src

Solution 3:

No, it is not possible, because the script file has no representation within the global javascript scope. You can only find its element inside the DOM as shown by haitaka, but this is a highly non-standard and certainly not recommended way to pass parameters to script.

Solution 4:

I know this is old, but I thought you wouldn't mind (yet another) two more cents...

If you are NOT adding an id to the script element, James Smith has a snippet that does not require an id attribute. And that id-less characteristic is huge, because your script file does NOT need to couple with an ID in the caller's 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 {};
}