views:

341

answers:

1

So if i am setting up a yahoo pipes badge on my site, yahoo gives me this code

<script src="http://pipes.yahoo.com/js/listbadge.js"&gt;{"pipe_id":"USER_ID","_btype":"list"}&lt;/script&gt;

Notice its passing an object literal to the remote script. i would like to do something similar with my own scripts, how do you interact with that input?

+1  A: 

You can't actually pass variables around like that natively. What Yahoo is doing there is that in their listbadge.js file, it searches through all the <script> tags on the page until it finds the one which included it, and then parses the innerHTML as JSON.

Their source has been slightly obfuscated, but here's my best understanding of it.

var scripts = document.getElementsByTagName("SCRIPT");

for (var i = 0; i < scripts.length; i++) {
    var includeString = scripts[i].src;
    if (includeString.match("listbadge.js")) {
        if (scripts[i].innerHTML){
            var passedVariables = parseJson(scripts[i].innerHTML);
        }
        break;
    }
}
nickf
that makes sense, Thanks!
Cipher
I was just wondering. Why JSON? the code is in the script tags so it could be a javascript object with a name to start with. Then you could just access the object by name from the loaded script. What's the point in parsing JSON?
Gene
the contents of the script tag are ignored when there is a src attribute specified.
nickf
Where is the added value on this approach when compared to adding another script tag with the object you want to access?
Gene
@Gene: saves about 80 bytes if content is encoded with Unicode :-) I suppose, if 80 less bytes are important to you, then fill your boots! Otherwise, I don't know. :-)
Lloyd Cotten
Actually, it doesn't really save that or anything, since you've got to have a function as demonstrated above to parse it out.
Lloyd Cotten
it keeps everything together - plus, you don't have to worry about conflicts in the global namespace.
nickf