How to pass parameters to a Script tag?

JavascriptParametersWidgetXssScript Tag

Javascript Problem Overview


I read the tutorial DIY widgets - How to embed your site on another site for XSS Widgets by Dr. Nic.

I'm looking for a way to pass parameters to the script tag. For example, to make the following work:

<script src="http://path/to/widget.js?param_a=1&amp;param_b=3"></script>

Is there a way to do this?


Two interesting links:

Javascript Solutions


Solution 1 - Javascript

I apologise for replying to a super old question but after spending an hour wrestling with the above solutions I opted for simpler stuff.

<script src=".." one="1" two="2"></script>

Inside above script:

document.currentScript.getAttribute('one'); //1
document.currentScript.getAttribute('two'); //2

Much easier than jquery OR url parsing.

You might need the polyfil for doucment.currentScript from @Yared Rodriguez's answer for IE:

document.currentScript = document.currentScript || (function() {
  var scripts = document.getElementsByTagName('script');
  return scripts[scripts.length - 1];
})();

Solution 2 - Javascript

It's better to Use feature in html5 5 data Attributes

<script src="http://path.to/widget.js" data-width="200" data-height="200">
</script>

Inside the script file http://path.to/widget.js you can get the paremeters in that way:

<script>
function getSyncScriptParams() {
         var scripts = document.getElementsByTagName('script');
         var lastScript = scripts[scripts.length-1];
         var scriptName = lastScript;
         return {
             width : scriptName.getAttribute('data-width'),
             height : scriptName.getAttribute('data-height')
         };
 }
</script>

Solution 3 - Javascript

Got it. Kind of a hack, but it works pretty nice:

var params = document.body.getElementsByTagName('script');
query = params[0].classList;
var param_a = query[0];
var param_b = query[1];
var param_c = query[2];

I pass the params in the script tag as classes:

<script src="http://path.to/widget.js" class="2 5 4"></script>

http://feather.elektrum.org/book/src.html">This article helped a lot.

Solution 4 - Javascript

Another way is to use meta tags. Whatever data is supposed to be passed to your JavaScript can be assigned like this:

<meta name="yourdata" content="whatever" />
<meta name="moredata" content="more of this" />

The data can then be pulled from the meta tags like this (best done in a DOMContentLoaded event handler):

var data1 = document.getElementsByName('yourdata')[0].content;
var data2 = document.getElementsByName('moredata')[0].content;

Absolutely no hassle with jQuery or the likes, no hacks and workarounds necessary, and works with any HTML version that supports meta tags...

Solution 5 - Javascript

JQuery has a way to pass parameters from HTML to javascript:

Put this in the myhtml.html file:

<!-- Import javascript -->
<script src="//code.jquery.com/jquery-1.11.2.min.js"></script>
<!-- Invoke a different javascript file called subscript.js -->
<script id="myscript" src="subscript.js" video_filename="foobar.mp4">/script>

In the same directory make a subscript.js file and put this in there:

//Use jquery to look up the tag with the id of 'myscript' above.  Get 
//the attribute called video_filename, stuff it into variable filename.
var filename = $('#myscript').attr("video_filename");

//print filename out to screen.
document.write(filename);

Analyze Result:

Loading the myhtml.html page has 'foobar.mp4' print to screen. The variable called video_filename was passed from html to javascript. Javascript printed it to screen, and it appeared as embedded into the html in the parent.

jsfiddle proof that the above works:

http://jsfiddle.net/xqr77dLt/

Solution 6 - Javascript

If you are using jquery you might want to consider their data method.

I have used something similar to what you are trying in your response but like this:

<script src="http://path.to/widget.js" param_a = "2" param_b = "5" param_c = "4">
</script>

You could also create a function that lets you grab the GET params directly (this is what I frequently use):

function $_GET(q,s) {
    s = s || window.location.search;
    var re = new RegExp('&'+q+'=([^&]*)','i');
    return (s=s.replace(/^\?/,'&').match(re)) ? s=s[1] : s='';
}

// Grab the GET param
var param_a = $_GET('param_a');

Solution 7 - Javascript

Create an attribute that contains a list of the parameters, like so:

<script src="http://path/to/widget.js" data-params="1, 3"></script>

Then, in your JavaScript, get the parameters as an array:

var script = document.currentScript || 
/*Polyfill*/ Array.prototype.slice.call(document.getElementsByTagName('script')).pop();

var params = (script.getAttribute('data-params') || '').split(/, */);

params[0]; // -> 1
params[1]; // -> 3

Solution 8 - Javascript

it is a very old thread, I know but this might help too if somebody gets here once they search for a solution.

Basically I used the document.currentScript to get the

Solution 9 - Javascript

Thanks to the jQuery, a simple HTML5 compliant solution is to create an extra HTML tag, like div, to store the data.

HTML:

<div id='dataDiv' data-arg1='content1' data-arg2='content2'>
  <button id='clickButton'>Click me</button>
</div>

JavaScript:

$(document).ready(function() {
    var fetchData = $("#dataDiv").data('arg1') + 
                    $("#dataDiv").data('arg2') ;

    $('#clickButton').click(function() {
      console.log(fetchData);
    })
});

Live demo with the code above: http://codepen.io/anon/pen/KzzNmQ?editors=1011#0

On the live demo, one can see the data from HTML5 data-* attributes to be concatenated and printed to the log.

Source: https://api.jquery.com/data/

Solution 10 - Javascript

This is the Solution for jQuery 3.4

<script src="./js/util.js" data-m="myParam"></script>
$(document).ready(function () {
    var m = $('script[data-m][data-m!=null]').attr('data-m');
})

Solution 11 - Javascript

Put the values you need someplace where the other script can retrieve them, like a hidden input, and then pull those values from their container when you initialize your new script. You could even put all your params as a JSON string into one hidden field.

Solution 12 - Javascript

I wanted solutions with as much support of old browsers as possible. Otherwise I'd say either the currentScript or the data attributes method would be most stylish.

This is the only of these methods not brought up here yet. Particularly, if for some reason you have great amounts of data, then the best option might be:

localStorage

/* On the original page, you add an inline JS Script.
 * If you only have one datum you don't need JSON:
 * localStorage.setItem('datum', 'Information here.');
 * But for many parameters, JSON makes things easier: */
var data = {'data1': 'I got a lot of data.',
            'data2': 'More of my data.',
            'data3': 'Even more data.'};
localStorage.setItem('data', JSON.stringify(data));

/* External target JS Script, where your data is needed: */
var data = JSON.parse(localStorage.getItem('data'));
console.log(data['data1']);

localStorage has full modern browser support, and surprisingly good support of older browsers too, back to IE 8, Firefox 3,5 and Safari 4 [eleven years back] among others.

If you don't have a lot of data, but still want extensive browser support, maybe the best option is:

Meta tags [by Robidu]

/* HTML: */
<meta name="yourData" content="Your data is here" />

/* JS: */
var data1 = document.getElementsByName('yourData')[0].content;

The flaw of this, is that the correct place to put meta tags [up until HTML 4] is in the head tag, and you might not want this data up there. To avoid that, or putting meta tags in body, you could use a:

Hidden paragraph

/* HTML: */
<p hidden id="yourData">Your data is here</p>

/* JS: */
var yourData = document.getElementById('yourData').innerHTML;

For even more browser support, you could use a CSS class instead of the hidden attribute:

/* CSS: */
.hidden {
   display: none;
}

/* HTML: */
<p class="hidden" id="yourData">Your data is here</p>

Solution 13 - Javascript

It's simpler if you pass arguments without names, just like function calls.

In HTML:

<script src="abc.js" data-args="a,b"></script>

Then, in JavaScript:

const args=document.currentScript.dataset.args.split(',');

Now args contains the array ['a','b']. This assumes synchronous script calling.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionTomer LichtashView Question on Stackoverflow
Solution 1 - JavascriptProbablePrimeView Answer on Stackoverflow
Solution 2 - JavascriptOBenderView Answer on Stackoverflow
Solution 3 - JavascriptTomer LichtashView Answer on Stackoverflow
Solution 4 - JavascriptRobiduView Answer on Stackoverflow
Solution 5 - JavascriptEric LeschinskiView Answer on Stackoverflow
Solution 6 - Javascriptrg88View Answer on Stackoverflow
Solution 7 - JavascriptMysticalView Answer on Stackoverflow
Solution 8 - JavascriptYared RodriguezView Answer on Stackoverflow
Solution 9 - Javascriptgagallo7View Answer on Stackoverflow
Solution 10 - Javascriptru4ertView Answer on Stackoverflow
Solution 11 - JavascriptbwestView Answer on Stackoverflow
Solution 12 - JavascriptFomView Answer on Stackoverflow
Solution 13 - JavascriptDavid SpectorView Answer on Stackoverflow