How to pass parameters to a Script tag?

139,594

Solution 1

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>

This article helped a lot.

Solution 2

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 3

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 4

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

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/

Share:
139,594
Tomer Lichtash
Author by

Tomer Lichtash

Web Developer, Israel

Updated on July 02, 2021

Comments

  • Tomer Lichtash
    Tomer Lichtash almost 3 years

    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:

  • Tomer Lichtash
    Tomer Lichtash about 13 years
    Thanks for answering. The params are actually input by the users (who embeds this script tag in their code). What then?
  • bwest
    bwest about 13 years
    The only thing I can think of if you don't have control over both client/server scripts is to take the users input and use it to generate a specific .js file with their input embedded in it, and that's assuming you are in control of gathering and processing their input.
  • Bartłomiej Skwira
    Bartłomiej Skwira about 10 years
    The article is awesome!
  • kspacja
    kspacja about 9 years
    Classes should be used to styling element not to pass parameters.
  • Pathros
    Pathros almost 9 years
    What if the id="myAwesomeWigretNo1" is not alwas like that but myAwesomeWigretNo2, or myAwesomeWigretNo681 ??? How can I fix this to accept a real variable?
  • Jason C
    Jason C over 8 years
    @kspacja Yeah and HTML should contain content only without styling, except we have to precisely order our DIV tags for float and column layouts because CSS can't actually do the job, and we're somehow OK with that. Hack away, I say. But you can use "data-" attributes if you want to avoid conflict or you're the type to lose sleep over it.
  • Dehli
    Dehli over 8 years
    Note that currentScript does not work in IE. Details
  • ProbablePrime
    ProbablePrime over 8 years
    I did add an polyfill for IE in the answer. Does the polyfill not work?
  • Thunderforge
    Thunderforge over 8 years
    For what it's worth, there are other ways to reference the script instead, such as document.currentScript (only works for scripts not in their own file) and putting an id on the <script> tag and then finding it by that.
  • OBender
    OBender over 8 years
    And what if the ID was changed by some other programmer in your team that had no clue that you use this id ?
  • takendarkk
    takendarkk about 8 years
    It's also not compliant with HTML5.
  • ProbablePrime
    ProbablePrime about 8 years
    Do you have a source for that this says its ok.
  • Luca Borrione
    Luca Borrione almost 8 years
    If you load scripts asynchronously then using an ID is the only reliable option I would recommend. Thanks @Thunderforge ... Also, any programmer should refrain from refactoring a code without a proper sprint plan overviewed by someone who has a clue of what's going on ;)
  • OBender
    OBender almost 8 years
    Sure you can demand a strong Ethics from Developers, but it wont work on the long run... People forget stuff.... In a Good Software Design Each Block Shod be isolated, awesome-pixels.tumblr.com/post/101930002170/… en.wikipedia.org/wiki/SOLID_(object-oriented_design) So I don't argue that it's a good vs bad solution it just more complex to maintain ID's vs not to maintain :-) Is you don't plan to load the script Async I see no reason to load using ID
  • OBender
    OBender over 7 years
    For async you can use this technique: stackoverflow.com/questions/12820953/…
  • Erik Kalkoken
    Erik Kalkoken about 7 years
    Went through some of the other solutions, but this was the one that worked the best and also is pretty simple to implement. thanks!
  • fadomire
    fadomire about 7 years
    the polyfill does not work anymore, document.currentScript is read only and cannot be assigned if it already exist. maybe a different check like if(!document.currentScript) { *** the polyfill function *** } would work better
  • Tim S
    Tim S over 6 years
    This should be the accepted solution, as it allows you to reference the script by ID and is valid HTML5.
  • Joe Eifert
    Joe Eifert over 5 years
    Does it become HTML5 compliant if you rename one and two to data-one and data-two?
  • arios
    arios over 5 years
    I thought this method was by far the easiest method them all. It works like a charm and gives me exactly what I need. Great question and Fantastic solution!
  • David Spector
    David Spector over 5 years
    Doesn't answer original question: doesn't use path/to/widget.js.
  • ProbablePrime
    ProbablePrime over 5 years
    My apologies David, I always make my answers generic so that others can use the solution without the initial implementation details adding to issues. In my example above you can see src="..." This is meant to signify, ANY src, doesn't matter :)
  • Skintest
    Skintest almost 5 years
    @RichardFox thanks for the answer, but just had to comment that "Doesn't answer original question: doesn't use path/to/widget.js" is probably the funniest thing I've read all week! Can't believe you replied as nicely as you have done.
  • Bob9630
    Bob9630 almost 5 years
    @fadomire a true polyfill should check for existence before polyfilling. Just wrap it in something like: if(!document.currentScript) {...}
  • Tronathan
    Tronathan over 4 years
    What are the downsides to this approach?
  • Mystical
    Mystical over 4 years
    @Tronathan there are no real downsides to this approach and there is a polyfill included for better browser support. The only downside I see here is not being able to include commas in parameters, which isn't usually a problem, and you can compensate for that by changing the delimiter to a character you aren't planning on using.
  • David Spector
    David Spector almost 3 years
    I think requiring a line before <script> for each parameter is clumsy. We need a new standards feature.
  • David Spector
    David Spector almost 3 years
    Requiring a line for each argument is clumsy, however the args are stored.
  • Fom
    Fom almost 3 years
    That's true David. I added JSON to the first method, making it more efficient for many arguments.
  • David Spector
    David Spector almost 3 years
    In my answer I show an easy way if you can do without the argument names.
  • Carnix
    Carnix over 2 years
    Except jQuery is effectively obsolete and has been for quite a while, besides the original question doesn't ask for a jQuery solution. You solution would better be written using document.querySelector().getAttribute() -- which was already mentioned in other answers. (not that it's the "best" way, just pointing out that a jQuery solution is not really necessary.
  • pfincent
    pfincent over 2 years
    if ".currentScript" doesn't work, you can instead just give an ID to the script tag, and access the data via "document.getElementByID(...).getAttribute(...)"