How to pass parameters to a Script tag?
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:
Comments
-
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&param_b=3"></script>
Is there a way to do this?
Two interesting links:
-
Tomer Lichtash about 13 yearsThanks for answering. The params are actually input by the users (who embeds this script tag in their code). What then?
-
bwest about 13 yearsThe 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 about 10 yearsThe article is awesome!
-
kspacja about 9 yearsClasses should be used to styling element not to pass parameters.
-
Pathros almost 9 yearsWhat if the id="myAwesomeWigretNo1" is not alwas like that but
myAwesomeWigretNo2
, ormyAwesomeWigretNo681
??? How can I fix this to accept a real variable? -
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 over 8 yearsNote that currentScript does not work in IE. Details
-
ProbablePrime over 8 yearsI did add an polyfill for IE in the answer. Does the polyfill not work?
-
Thunderforge over 8 yearsFor 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 anid
on the<script>
tag and then finding it by that. -
OBender over 8 yearsAnd what if the ID was changed by some other programmer in your team that had no clue that you use this id ?
-
takendarkk about 8 yearsIt's also not compliant with HTML5.
-
ProbablePrime about 8 yearsDo you have a source for that this says its ok.
-
Luca Borrione almost 8 yearsIf 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 almost 8 yearsSure 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 over 7 yearsFor async you can use this technique: stackoverflow.com/questions/12820953/…
-
Erik Kalkoken about 7 yearsWent through some of the other solutions, but this was the one that worked the best and also is pretty simple to implement. thanks!
-
fadomire about 7 yearsthe 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 over 6 yearsThis should be the accepted solution, as it allows you to reference the script by ID and is valid HTML5.
-
Joe Eifert over 5 yearsDoes it become HTML5 compliant if you rename
one
andtwo
todata-one
anddata-two
? -
arios over 5 yearsI 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 over 5 yearsDoesn't answer original question: doesn't use path/to/widget.js.
-
ProbablePrime over 5 yearsMy 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 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 almost 5 years@fadomire a true polyfill should check for existence before polyfilling. Just wrap it in something like: if(!document.currentScript) {...}
-
Tronathan over 4 yearsWhat are the downsides to this approach?
-
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 almost 3 yearsI think requiring a line before <script> for each parameter is clumsy. We need a new standards feature.
-
David Spector almost 3 yearsRequiring a line for each argument is clumsy, however the args are stored.
-
Fom almost 3 yearsThat's true David. I added JSON to the first method, making it more efficient for many arguments.
-
David Spector almost 3 yearsIn my answer I show an easy way if you can do without the argument names.
-
Carnix over 2 yearsExcept 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 over 2 yearsif ".currentScript" doesn't work, you can instead just give an ID to the script tag, and access the data via "document.getElementByID(...).getAttribute(...)"