How do I get query string value from script path?

I am adding my Javsacript file in pages with different query strings in the script path like this:

Page1:

<script type="text/javascript" src="file.js?abc=123"></script>

Page2:

<script type="text/javascript" src="file.js?abc=456"></script>

Page3:

<script type="text/javascript" src="file.js?abc=789"></script>

In my Javascript file, how can I get the value of the "abc" param? I tried using window.location for this, but that does not work.

In case it helps, below is a function I use to find the value of a query string param:

function getQuerystring(key, defaultValue) {
    if (defaultValue == null) defaultValue = "";
    key = key.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
    var regex = new RegExp("[\\?&]" + key + "=([^&#]*)");
    var qs = regex.exec(window.location.href);
    if (qs == null)
        return defaultValue;
    else
        return qs[1];
}

Answers:

Answer

This is possible. See Passing JavaScript arguments via the src attribute. The punchline is that since scripts in HTML (not XHTML) are executed as loaded, this will allow a script to find itself as it is always the last script in the page when it’s triggered–

var scripts = document.getElementsByTagName('script');
var index = scripts.length - 1;
var myScript = scripts[index];
// myScript now contains our script object
var queryString = myScript.src.replace(/^[^\?]+\??/,'');

Then you just apply the query string parsing.

Answer

First, the technical answer: if you assign your script tag an ID, you can then grab its src and then parse out the query string.

<script id="whatever" type="text/javascript" src="file.js?abc=123"></script>

 

var path = document.getElementById('whatever').src;
// ...

With that answered, I'd like to voice my concern — this reeks of poor design decisions. Why are you including your script this way (with a querystring)? If you're trying to optimize your site (by having one large script that can be cached for subsequent pages), this approch is actually counter-productive because browsers will make a fresh request for the script file on each page due to the differing query string. The correct approach is to have one large shared file and then a small page-specific file on each page.

Answer

I have a quick and easy solution for extracting the query string from a js file using jQuery to grab the script tag source attribute and simply using two separate functions for parsing the JS file path and query string. Obviously, jQuery is required.

$(document).ready(function() {

    var p = parseURL($('script[src*="thisfile.js"]').attr('src'));

    console.log(p);

});

// Parse a URL into its parts
function parseURL(url)
{
    var p = document.createElement('a');

    p.href = url;

    var obj = {
        'protocol' : p.protocol,
        'hostname' : p.hostname,
        'port' : p.port,
        'pathname' : p.pathname,
        'search' : p.search,
        'query' : p.search.substring(1),
        'args' : parseStr(p.search.substring(1)),
        'hash' : p.hash,
        'host' : p.host
    };

    return obj;
}

// Parse a query string
function parseStr(string)
{
    var args = string.split('&');
    var argsParsed = {};

    for (i = 0; i < args.length; i++)
    {
        var arg = decodeURIComponent(args[i]);

        if (arg.indexOf('=') == -1)
        {
            argsParsed[arg.trim()] = true;
        }
        else
        {
            var kvp = arg.split('=');
            argsParsed[kvp[0].trim()] = kvp[1].trim();
        }
    }

    return argsParsed;
}

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.