I have an external JavaScript file that I load from my HTML pages in the usual way (i.e. by using a script tag that as its src attribute provides an URL to the JavaScript file).
In that URL, I want to include a query parameter and from within the JavaScript have access to the value of that query parameter.
Note - I have found answers to how to handle URL query parameters from a URL in general, but note that this question concerns one specific URL, namely the one that is used to load the JavaScript file in question, compare to using argc and argv in C.
1 Answer
If your calling document has this data, put it in a JavaScript variable, then use this in the incorporated code via, for example, a function call.
const value = ...;
imported(value)
Remember, the JavaScript itself only runs in the current document, not on some remote machine doing mysterious remote machine things.
There is no argv equivalent since the JavaScript is normally just a static file, the server it's requested from does not care about the contents in any way, and does not run it. That's your job when you incorporate it via <script>, you're the caller.
I'm expecting this is your implied approach:
<script src="https://example.com/script.js?value=..."></script>
Sending it in as a GET parameter is completely pointless, the server you're fetching the static JavaScript file from likely doesn't care. They get ignored. I've only seen these used for "cache busting" to ensure the most recent version of the file is loaded.
You could also keep the parameter as a data property on some element.
4 Comments
data properties or other attributes), or both. You can't communicate anything of value in the src property.
/page.html?param1=fooand it links to the JS/script.js?param2=barare you interested in gettingparam1orparam2?argc/argvis fairly pointless, since the execution mechanism is completely different. It'd help if you provided more context here, so we can propose an actual solution rather than taking stabs into the dark.