Skip to content
Back to Blog

Passing arguments to embedded JavaScript

Rich Jones

Jan 2, 2017 9:30:00 AM

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.

Method 1: HTML5 'data' Attribute

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="" >

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.

Method 2: Use the QueryString

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" 

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?

Written By:

Rich Jones

Want to get our totally not sh*tty weekly newsletter?

Sometimes The Wayfarer is funny, sometimes insightful, but always the least spammy newsletter this side of Tatooine.