20

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?

Adam Halasz
  • 57,421
  • 66
  • 149
  • 213
  • You'd have to use the server AFAIK, but why not just set the appropriate JS variables in a separate ` – Pekka Mar 05 '13 at 12:33

8 Answers8

16

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]);
}
haitaka
  • 1,832
  • 12
  • 21
15

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

document.currentScript.src
Igari Takeharu
  • 371
  • 3
  • 4
7

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.

Jiri Tobisek
  • 579
  • 3
  • 5
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 {};
}
RayLuo
  • 17,257
  • 6
  • 88
  • 73
2

You can use document.currentScript.src (only at the appropriate time) and URLSearchParams to extract the query string from the called JavasScript file.

Example:

In your HTML:

<script src="querystring.js?foo=bar&foo=bar2"></script>

In your JavaScript file:

/**
 * When this is being run, the document's last element will be this very script.
 * Explanations on http://feather.elektrum.org/book/src.html
 */
var scripts = document.getElementsByTagName('script');
var index = scripts.length - 1;
var myScript = scripts[index];
  // document.currentScript.src will be this file's URL, including its query string.
  // e.g. file:///mytests/querystring.js?foo=script

/**
 * Now just turn the query string (if any) into a URLSearchParams
to let us easily check values.
 */
var querystring = document.currentScript.src.substring( document.currentScript.src.indexOf("?") );
var urlParams = new URLSearchParams( querystring );

console.log( urlParams.getAll('foo') ); // Array [ "bar", "bar2" ]

Keep in mind:

  • This might not work when the script is included via async.
  • get or getAll?
    • urlParams.get will only return the first value (as a string)
    • urlParams.getAll will return an array (of size 1 if just one value is provided.)

I hope this helps.

Fabien Snauwaert
  • 4,995
  • 5
  • 52
  • 70
0

I know this is old, but I thought I'd throw in my two cents...

If you are already adding an id to the script element, why not add a custom attribute as well:

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

Then you can grab the value using getAttribute:

document.getElementById('query').getAttribute('value');
jacobfogg
  • 309
  • 2
  • 9
0

When an HTML file uses a Script tag with a src attribute that includes a query string to load a JavaScript program, you cannot use location.search to retrieve the query string, because location does not contain the URL (as it does with the href attribute). The URL can be obtained using "new URL(here.src).search", where "here" is a string you use in the Script id attribute.

Thus, one solution (from another answer elsewhere, that does not decode the arguments) is

var queryDict = {};
new URL(here.src).search.substr(1).split("&").forEach(function(item) {queryDict[item.split("=")[0]] = item.split("=")[1]})

After running this code, queryDict is an object containing the argument property/value pairs.

David Spector
  • 1,520
  • 15
  • 21
-3

Try like this to get the value of query using javascript

alert(window.location.href.split["?"][1].split["="][1]);
Dineshkani
  • 2,899
  • 7
  • 31
  • 43