Get parameters to HTML page with JavaScript

If you have a static HTML page that you need to pass a parameter so that it can be updated easily or work in different instances, this post will show you how to get the parameters via the URL into JavaScript without the use of a backend server.

document.URL contains the entire address bar of the browser, and you can parse this to get the parameters and do something useful with it.

Below is the snippet of code I worked up to do this for a mockup/demo that we were working on for work.  Specifically, we wanted to have a single HTML page that would load the same Flex player with different parameters (and wanted to pass those parameters in via the URL) so that we could test with current and future streams/video sources.

<html>
<head>
    <script>
        function pageLoaded() {
            var qAt = document.URL.indexOf("?");
            var params = document.URL.substr(qAt+1);
            // Use params as needed (parse, or pass along to flash swf):
            alert(params);  // just echoing in this example.
        }
    </script>
</head>
<body onload="pageLoaded()">
</body>
</html>

2 Responses to “Get parameters to HTML page with JavaScript”

  1. Roger June 11, 2014 at 2:10 pm #

    Very nice and thanks. After searching through lots of crap, yours is really a gold nugget. Just one question simply out of curiosity, what does “qAt” stand for? Again it worked like champ. Many thanks, you saved lots of my time.

  2. Jeremy Snyder June 12, 2014 at 9:22 am #

    Roger, I honestly don’t recall the reasoning of that variable name…. “q” was probably for Query, but unsure why I used “At”. Happy to hear the post helped you!

Leave a Reply