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?

asked Jan 16, 2013 at 17:36
1
  • 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. Commented Jan 18, 2013 at 22:56

2 Answers 2

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
7,1645 gold badges46 silver badges94 bronze badges
answered Jan 16, 2013 at 17:43

1 Comment

picked this answer since it was a self contained function that's easy to drop in :)
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.

answered Jan 16, 2013 at 17:46

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.