
So, you're writing an embedded script and you want to pass some arbitrary arguments and parameters to your javascript. How do you do it? This quick little tutorial will show you two examples, one using the HTML5 data attribute, and the other using the query string.
This is the easiest method. HTML5 now supports arbitrary parameters as long as they are prefixed with 'data-', so you can pass any arguments to your function with that.
So, your embed will look like this:
<script id="searcher" data-search="bananas"
src="http://yoursite.io/searcher.js" >
Then, inside your javascript:
var script_tag = document.getElementById('searcher')
var search_term = script_tag.getAttribute("data-search");
And that's it! Easy peasy.
The downside of this is that some very very old browsers might not like your arbitrary HTML5 attributes. In that case, you can use the querystring approach.
In this case, you're just going to pass your parameters to the javascript as part of the query string, just like on any other GET request.
So, your embedded script tag will look like this: So, your embed will look like this:
<script id="searcher"
src="http://yoursite.io/searcher.js?search=bananas">
Then, your JavaScript will look like this:
var script_tag = document.getElementById('searcher');
var query = script_tag.src.replace(/^[^\?]+\??/,'');
// Parse the querystring into arguments and parameters
var vars = query.split("&");
var args = {};
for (var i=0; i<vars.length; i++) {
var pair = vars[i].split("=");
// decodeURI doesn't expand "+" to a space.
args[pair[0]] = decodeURI(pair[1]).replace(/\+/g, ' ');
}
var search_term = args['search'];
And that's it! It's slightly uglier than the previous method, but it'll work on older browsers. Probably.
And that's it! Did this work for you? Please leave any questions and comments below!

gun.io is where top developers find gigs. Bad developers are screened out, so you'll only hire great hackers at gun.io.
Pssst! Hackers, sign up here!
We match top developers with high-quality freelance and full-time jobs.


Sign up with GitHub and we'll match you with great gigs based on your open-source portfolio!
Pssst.. do you want to write for Gun.io? Or, do you have a blog you'd like to see syndicated here?
Get in touch!