0

Possible Duplicate:
Getting URL of executing JavaScript file (IE6-7 problem mostly)

Hi my page has this line:

<script type="text/javascript" src="pixel.js?name=Test&age=21"></script>

I need pixel.js to access the vairables name and age, how is this possible? I tried using address bar variable (get POST data) method but it comes out undefined as I imagine this isn't technically in the address bar...

Thanks Craig

Community
  • 1
  • 1
Craig
  • 431
  • 1
  • 4
  • 12
  • I agree this is a dup, but that question doesn't have a good answer (probably because there really isn't one). – Pointy Jun 06 '12 at 12:31
  • 1
    If you explain what you want to do overall, there's almost certainly a better, reliable way to do what you're doing. – Pointy Jun 06 '12 at 12:32
  • 1
    @Pointy If the other question is definitely a dupe but with no good answers, then we should work on improving the answers to that one (even if the definitive answer is "there is no solution"). – Dan Blows Jun 06 '12 at 12:36
  • @Blowski fair enough :-) – Pointy Jun 06 '12 at 12:36

4 Answers4

0

I think you cannot do this as long as pixel.js is a static file. If you want to do something like this you have to use some server handler to serve javascript files and read query string parameters.

AHMED EL-HAROUNY
  • 836
  • 6
  • 17
0

Do you need to pass variables from your HTML page to JavaScript or what are you doing?

IF you reallt need to do that check this tutorial: http://feather.elektrum.org/book/src.html

I actually found a similar discussion and swiped user378221's answer: Passing parameters to JavaScript files

I would recommend declaring your variables ina sperate script tag and then including the file.

Community
  • 1
  • 1
Peadar
  • 439
  • 4
  • 9
0

You can only do it by finding the script tag with your filename and then parsing the src attribute... something like this:

var scripts = document.getElementsByTagName('script'),
    scriptTest = /^pixel\.js/,
    pixelScript, params,
    getScriptParams = function(scriptSrc){
        var qSplit = scriptSrc.split('?'),
            aSplit = qSplit[1].split('&'),
            retVals = {}, pSplit;

        for (var i = 0, il = aSplit.length; i < il; i++) {
            pSplit = aSplit[i].split('=');
            retVals[pSplit[0]] = pSplit.length > 1 ? pSplit[1] : null;
        }

        return retVals;
    };

for (var i = 0, il = scripts.length; i < il; i++) {
    if (scriptTest.test(scripts[i].src)) {
        pixelScript = scripts[i];
    }
}

params = getScriptParams(pixelScript.src);
mVChr
  • 49,587
  • 11
  • 107
  • 104
0

Disclaimer: Not tested

Just put an ID on the script element and then grab it from the included script (they exist on the same DOM, so it should work)

HTML:

<script id="blah" type="text/javascript" src="foo.js?key=value" />

foo.js:

console.log(document.getElementById('blah').src);​

jbabey
  • 45,965
  • 12
  • 71
  • 94