Skip to content Skip to sidebar Skip to footer

Can You Pass Url Parameters To A Javascript File?

From within myscript.js, is there any way to obtain that someParameter was set to 123? Or is the only way to use

Solution 1:

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.

Solution 2:

Jquery Address does this, so i've been checking their code out and this is the improved solution I just created myself:

$.each($('script'), function(id, val){ //loop trough all script-elementsvar tmp_src = String($(this).attr('src'));//store the src-attrvar qs_index = tmp_src.indexOf('?');//check if src has a querystring and get the index//Check if the script is the script we are looking for and if it has QS-paramsif(tmp_src.indexOf('myscript.js') >= 0 && qs_index >= 0)
    {
        //this is myscript.js and has a querystring//we want an array of param-pairs: var1 = value1, var2 = value2, ...var params_raw = tmp_src.substr(qs_index + 1).split('&');

        //create empty options arrayvar options = [];

        //loop troug raw params
        $.each(params_raw, function(id, param_pair){
                    //split names from valuesvar pp_raw = param_pair.split('=');
                    //store in options array
            options[pp_raw[0]] = pp_raw[1];
        });
            //check the results out in the console!console.log(options);
    }
});

I hope this does what you need?

Post a Comment for "Can You Pass Url Parameters To A Javascript File?"