16

In my HTML file I have linked to the JS with:

src="myscript.js?config=true"

Can my JS directly read the value of this var like this?

alert (config);

This does not work, and the FireFox Error Console says "config is not defined". How do I read the vars passed via the src attribute in the JS file? Is it this simple?

Robin Rodricks
  • 99,791
  • 133
  • 372
  • 575
  • I use a Script tag in my HTML to include a JavaScript file, and I specify arguments in the src attribute. But on the JavaScript side, window.location doesn't include the arguments. How do I retrieve them? – David Spector Sep 12 '20 at 20:02

8 Answers8

19
<script>
var config=true;
</script>
<script src="myscript.js"></script>

You can't pass variables to JS the way you tried. SCRIPT tag does not create a Window object (which has a query string), and it is not server side code.

Matthew Flaschen
  • 255,933
  • 45
  • 489
  • 528
Itay Moav -Malimovka
  • 48,785
  • 58
  • 182
  • 262
6

Yes, you can, but you need to know the exact script file name in the script :

var libFileName = 'myscript.js',
    scripts = document.head.getElementsByTagName("script"), 
    i, j, src, parts, basePath, options = {};

for (i = 0; i < scripts.length; i++) {
  src = scripts[i].src;
  if (src.indexOf(libFileName) != -1) {
    parts = src.split('?');
    basePath = parts[0].replace(libFileName, '');
    if (parts[1]) {
      var opt = parts[1].split('&');
      for (j = opt.length-1; j >= 0; --j) {
        var pair = opt[j].split('=');
        options[pair[0]] = pair[1];
      }
    }
    break;
  }
}

You have now an 'options' variable which has the arguments passed. I didn't test it, I changed it a little from http://code.google.com/p/canvas-text/source/browse/trunk/canvas.text.js where it works.

Fabien Ménager
  • 139,874
  • 3
  • 38
  • 60
  • I'm struggling to think of a real-world use case where this would be more beneficial than Itay Moav's answer. – Andy E Jun 19 '09 at 11:31
  • 3
    In order to make a script easier to integrate. Personnaly I find it easier to pass a few http parameters (which aren't really ones) than having to declare a few variables in another script tag. – Fabien Ménager Jun 19 '09 at 11:42
4

You might have seen this done, but really the JS file is being preprocessed server side using PHP or some other language first. The server side code will print/echo the javascript with the variables set. I've seen a scripted ad service do this before, and it made me look into seeing if it can be done with plain ol' js, but it can't.

Andy E
  • 311,406
  • 78
  • 462
  • 440
4

You need to use Javascript to find the src attribute of the script and parse the variables after the '?'. Using the Prototype.js framework, it looks something like this:

var js = /myscript\.js(\?.*)?$/; // regex to match .js

var jsfile = $$('head script[src]').findAll(function(s) {
    return s.src.match(js);
}).each(function(s) {
    var path = s.src.replace(js, ''),
    includes = s.src.match(/\?.*([a-z,]*)/);
    config = (includes ? includes[1].split('=');
    alert(config[1]); // should alert "true" ??
});

My Javascript/RegEx skills are rusty, but that's the general idea. Ripped straight from the scriptaculous.js file!

Barry Gallagher
  • 5,865
  • 4
  • 24
  • 30
1

Your script can however locate its own script node and examine the src attribute and extract whatever information you like.

  var scripts = document.getElementsByTagName ('script');
  for (var s, i = scripts.length; i && (s = scripts[--i]);) {
    if ((s = s.getAttribute ('src')) && (s = s.match (/^(.*)myscript.js(\?\s*(.+))?\s*/))) {
      alert ("Parameter string : '" + s[3] + "'");    
      break;
    } 
  }
HBP
  • 14,098
  • 4
  • 25
  • 33
  • 1
    Wouldn't it be much simpler to give the script tag an ID and in it use document.getElementById ? – Itay Moav -Malimovka Jun 19 '09 at 11:43
  • Yes if you are the author of both the script and the web page calling it. My code fragment came from a generic library file and I do not want its users to have to use an id with the subsequent issues if it were specified incorrectly. – HBP Jun 19 '09 at 17:04
0

Using global variables is not a so clean or safe solution, instead you can use the data-X attributes, it is cleaner and safer:

<script type="text/javascript" data-parameter_1="value_1" ... src="/js/myfile.js"></script>

From myfile.js you can access the data parameters, for instance with jQuery:

var parameter1 = $('script[src*="myfile.js"]').data('parameter_1');

Obviously "myfile.is" and "parameter_1" have to match in the 2 sources ;)

Luca C.
  • 7,969
  • 67
  • 67
0

Whether or not this SHOULD be done, is a fair question, but if you want to do it, http://feather.elektrum.org/book/src.html really shows how. Assuming your browser blocks when rendering script tags (currently true, but may not be future proof), the script in question is always the last script on the page up to that point.

Then using some framework and plugin like jQuery and http://plugins.jquery.com/project/parseQuery this becomes pretty trivial. Surprised there's not a plugin for it yet.

Somewhat related is John Resig's degrading script tags, but that runs code AFTER the external script, not as part of the initialization: http://ejohn.org/blog/degrading-script-tags/

Credits: Passing parameters to JavaScript files , Passing parameters to JavaScript files

Community
  • 1
  • 1
Oskar Austegard
  • 4,536
  • 4
  • 34
  • 50
0

You can do that with a single line code:

new URL($('script').filter((a, b, c) => b.src.includes('myScript.js'))[0].src).searchParams.get("config")
Oğuzhan Türk
  • 336
  • 2
  • 7
  • 18