Possible to get query parameters of the <script> src JavaScript URL?
Asked Answered
H

1

7

As an example, I have the following html:

<body>
  <script src="code.js?q=xyz"></script>
</body>

I want to be able to read the q=xyz query parameter from within code.js. I tried:

console.log(window.location.href)

But it gives me the html document's URL, not code.js's URL (I could then parse the URL for the query parameters).

Is there any way to get an imported JavaScript file's query parameters from within that JavaScript? I know I could read the query parameters on a server and then send back JavaScript that has the query parameters embedded, but I don't want that. I want to be able to put JavaScript files on CDNs that can be configured via query parameters.

Hagi answered 18/11, 2016 at 0:10 Comment(2)
you want document.currentScriptMannes
Before you do that, you should check out this: #2191301Neil
H
10

You could use document.currentScript.src to access the <script>'s src-attribute and then extract the query parameter. For older browsers (such as IE 11) access the src-attribute by:

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

This will return the src-attribute of the last executed script. In some cases the last executed script is not the current script (for example, if a script manipulates other <script>-elements), and therefore it's a bit unreliable.

Hypallage answered 18/11, 2016 at 0:16 Comment(3)
Exactly what I was hoping existed! Thanks. Unfortunately IE 11 doesn't support document.currentScript: caniuse.com/#search=currentScript I normally wouldn't care about IE 11, but in this particular case I have to care... The only polyfill I found works on IE 6-10 and expressly doesn't work on IE 11 :( github.com/JamesMGreene/document.currentScript Any workaround for IE 11?Hagi
There's a workaround. I'll add it to the answer. I think this has been answered somewhere else on SO, tho - I can't locate the question.Hypallage
I could search all <script> tags and look for one with my URL... Then get the query parameters.Hagi

© 2022 - 2024 — McMap. All rights reserved.