2

Possible Duplicate:
JavaScript query string

I'd like to access query variables attached to my script url. So for example:

<script type="text/javascript" src="http://mysite.com/app.js?var1=value1&var2=value2"></script>

In app.js, how do I access the var1 and var2 values?

Community
  • 1
  • 1
Joe
  • 1,762
  • 9
  • 43
  • 60
  • I don't think this is an exact duplicate. The possible duplicate offered just asks how to manipulate the querystring in javascript -- this question is specific to the script tag. – mcknz Jan 18 '13 at 22:56

2 Answers2

2

This page describes a method for getting these values:

<script type="text/javascript"
        src="scriptaculous.js?load=effects,builder"></script>

And the javascript:

function getJSvars(script_name, var_name, if_empty) {
    var script_elements = document.getElementsByTagName(‘script’);

    if(if_empty == null) {
        var if_empty = ”;
    }

    for (a = 0; a < script_elements.length; a++) {
       var source_string = script_elements[a].src;
           if(source_string.indexOf(script_name)>=0) {

           var_name = var_name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
           var regex_string = new RegExp("[\\?&]"+var_name+"=([^&#]*)");
           var parsed_vars = regex_string.exec(source_string);
           if(parsed_vars == null) { return if_empty; }
           else { return parsed_vars[1]; }

          }
       }
    }
jpaugh
  • 6,634
  • 4
  • 38
  • 90
mcknz
  • 467
  • 9
  • 27
  • picked this answer since it was a self contained function that's easy to drop in :) – Joe Jan 16 '13 at 17:53
0

Parse the src attribute, roughly as follows:

var src=document.getELementById("script-id").getAttribute("src");
var query=src.substring(src.indexOf("?"));
var query_vals=query.split("&");
var queries={};
for (var i=0;i<query_vals.length;i++) {
  var name_val=query_vals.split("=");
  queries[name_val[0]]=name_val[1];
}
console.log(queries.var1, queries.var2);

However, there are libraries such as url.js which are a better bet for doing this, and much more robust in the face of URL encoding etc.