Search code examples
javascripturlparameters

Can you pass URL parameters to a Javascript file?


<script src="myscript.js?someParameter=123"></script>

From within myscript.js, is there any way to obtain that someParameter was set to 123? Or is the only way to use server side scripts that generate the javascript file with the parameters in it?


Solution

  • Well, you get URL parameters from window.location.href. As the name says, it refers to the current window. What the <script> tag does it to embed the linked file into the current document, thus into the same window. If you parsed window.location.href from the linked JavaScript file, you'd only get the URL from the embedding document.

    There are two ways to pass parameters to another JavaScript file:

    1. As @Dave Newton suggested, just declare a variable, then embed the JS file like you did (without the parameters of course, because they have no effect).
    2. Create an iframe, pass the parameters you want to the URL of the iframe, then embed the JavaScript file inside the iframe. An iframe will create a new window instance.