Using Script tags to do remote HTTP calls in Javascript

I’ve been racking my brains all afternoon trying to find a workable solution to the problem of not being able to make remote HTTP calls using javascript. This is an issue for me because so much of my work takes place inside a TiddlyWiki which, when viewed locally (from a file:// url) is a perfect environment for bypassing standard AJAX security and creating mashups. The problem comes when I want to put a TiddlyWiki online to show off what I’ve done or to let other people use it – the local behaviour is not replicated and my mashups go kaput.

There are several ways of getting around this security restriction, known as Javascript’s same-origin policy, but they generally involve using iframes and other files on your own server. I wanted to keep everything in one self-contained file, so I pretty much ruled these out. The idea of using a local proxy was thrown out for the same reasons.

A found a some info that covered “dynamic Script tags”, which requires the remote server to serve you a tailored javascript file that called a function you supplied the name of, with the data you wanted returned as a parameter to that function, but that was really just a facade on top of another proxy story.

Then I hit upon this wonderful website, which gave an insight into an API architecture being adapted by, amongst others, Yahoo!. The idea revolves around the API itself returning JSON encapsulated in a function call, so the body of the response is essentially the parameter to the function. You add a Script tag to your page with the API call as the src attribute and when the browser loads the script, it ends up calling the function, which you write support for in your code.

// adapted from http://www.hunlock.com/blogs/Howto_Dynamically_Insert_Javascript_And_CSS
var headID = document.getElementsByTagName("head")[0];         
var newScript = document.createElement('script');
newScript.type = 'text/javascript';
newScript.onload=scriptLoaded;
newScript.src = 'http://api.flickr.com/services/feeds/photos_public.gne?tags=sunset&format=json';
headID.appendChild(newScript);

jsonFlickrFeed = function(feed) {
   // deal with the feed!
};

// when the script is finished, remove the script node we added
// removeNode is a custom function defined in the TiddlyWiki source code: http://svn.tiddlywiki.org/Trunk/core/js/Dom.js
// It ensures that the eventhandler is removed before deletion
scriptLoaded = function() {
	removeNode(newScript);
};

It’s simple, elegant and easy to work with. There are two alternative implementations that I’ve seen today: the first and simplest for the server to support, is exemplified by Flickr – the function call wrapped around the response data is fixed and you have to know what it is to write support for it [edit - they do support the next method too]; Yahoo! Pipes (and more generally, Yahoo!’s other developer API’s) supports the second method – the API takes the name of a callback function as a parameter and then wraps the data in a call to this function, which takes away the dependency on knowing the specific function to write support for.

This isn’t the perfect solution, as it leaves you wide open to exploitation from cross-site scripting, so I don’t recommend using this with API’s that you don’t trust. I feel pretty safe using Yahoo!’s API’s, but someone less salubrious could inject whatever they wanted in there. You don’t really want that when the script has access to the global object and, therefore, everything on your page.

This takes me one step closer to making it easier to replicate your offline TiddlyWiki environment online… Hurrah…

About these ads

23 Comments

  1. Posted September 17, 2007 at 6:49 pm | Permalink

    The only problem I encountered with dynamic insertion of script tags was a lack of support in Safari. At least that was v2, I don’t know if they’ve fixed/changed that in the v3 betas. I suppose I ought to investigate/try it out.

    The JSON sent back in a call back function is nifty – a guy wrote a version of my flickr dom badge using that.

  2. Posted September 18, 2007 at 9:37 am | Permalink

    Hey, that’s cool. I’m really interested in how you did the funky 3D view of your code in the title bar.

  3. Posted September 18, 2007 at 10:45 am | Permalink

    The 3D view is a simple “screw around with a text block in Fireworks with the skew tool”. I can throw up the source png somewhere if you want to have a look at it.

  4. Posted September 18, 2007 at 12:10 pm | Permalink

    Jon, suggest checking out the JSONP convention as well. One of the issues with JSON is that a JSON response alone is useless – the third party’s Javascript has to do something with it at the end, like call a callback method.

  5. Posted September 18, 2007 at 5:33 pm | Permalink

    Cheers Patrick, that’d be interesting. I’m no Fireworks expert, so I thought you’d done some wicked image manipulation programmatically… although technically I guess you did.

  6. Posted September 18, 2007 at 5:37 pm | Permalink

    Michael, ok, that’s pretty interesting… what does JSONP let you do that wouldn’t be enabled by the JSON returning a custom callback function?

  7. i wasn't at your persc%nto presentation
    Posted September 21, 2007 at 10:33 am | Permalink

    can i flag up a major tech post of the month here?

    surely there must be someway of deploying directly from your local server on a lightweight system like jetty. of course I have little experience with JS and have just blasted through it first time… at least my first point is valid!

  8. Posted September 24, 2007 at 1:36 pm | Permalink

    Thanks! Ok, so I’m not with you yet – Jetty’s a Java-based web server, right? What are you referring to when you say “deploying directly from your local server”? The problem I’m trying to solve here is the restriction on javascript running in a browser…

  9. Luis
    Posted November 13, 2007 at 9:59 am | Permalink

    Hey, As the first guy said, current KHTML browsers lack of execution in the script tag, and depends on your page statistics this is requirement (5%).

    So, doesn’t this finally mean that I have to setup a proxy and make a simple XHR call?

  10. Posted June 2, 2009 at 12:02 pm | Permalink

    I just read your post on Appjet closing. There is an app I wrote on appjet that does JavaScript remoting for any webpage.

    http://json-proxy.appjet.net/

    For example, if you want to get google.com:

    So callback() would receive google.com’s html as a string.

    Too bad it won’t be up for long.

  11. Posted March 23, 2013 at 8:32 am | Permalink

    When I originally commented I clicked the “Notify me when new comments are added” checkbox
    and now each time a comment is added I get four emails with the same
    comment. Is there any way you can remove me from that service?
    Thanks a lot!

  12. Posted March 23, 2013 at 10:55 pm | Permalink

    Wonderful beat ! I would like to apprentice whilst you amend your web site,
    how can i subscribe for a weblog web site? The account helped me
    a applicable deal. I had been a little bit familiar of this your
    broadcast provided bright transparent idea

  13. Posted March 28, 2013 at 7:44 am | Permalink

    Some people known as Nikon one V1 a conveyable DSLR the place
    you are able to just slip correct by way of your pocket but its shooting strength is identical as that of a DSLR.
    Samsung M620 Black mobile is just big enough to display
    four icons side by side and measures only 1. s r CMOS sensor, BIONZ impression processor chip in
    addition to a Sony Grams contact with powerful (10x optical move, 25-250 mm range) wide-angel mega-zoom (26 mm) help in
    choosing stunning golf swings quite possibly with low-light circumstances.

  14. Posted April 25, 2013 at 6:41 pm | Permalink

    Why viewers still make use of to read news papers when in this technological globe everything is existing on net?

  15. Posted April 25, 2013 at 8:58 pm | Permalink

    Your next step is to include more of it in your cooking
    or get it from supplements. Weight Control: Capsaicin speeds up metabolism which helps the body
    to burn more calories faster. This is absolute fantastic news
    for the whole world and should cause everyone to include this
    delicious spice to their palate.

  16. Posted April 28, 2013 at 3:45 am | Permalink

    If you have cracked heels, take the peel
    and rub the inside on and around the cracks. A
    good facial moisturizer is a critical part of daily face care routine,
    and as part of a facial cream or facial moisture oil, almond
    oil gives extra nourishment needed without feeling oily or weighted down.
    Used in combination with other vegetable oils to produce a nice, hard bar of
    soap.

  17. Posted May 3, 2013 at 5:56 am | Permalink

    Greate article. Keep writing such kind of information on your blog.
    Im really impressed by it.
    Hey there, You have performed an incredible job.

    I’ll certainly digg it and personally recommend to my friends. I am confident they’ll be benefited from this web
    site.

  18. Posted May 7, 2013 at 11:39 pm | Permalink

    Fantastic goods from you, man. I’ve take note your stuff previous to and you are just extremely fantastic. I really like what you have obtained right here, certainly like what you’re saying
    and the way in which in which you are saying it.
    You make it enjoyable and you still care for to keep it sensible.
    I can not wait to read much more from you. This is actually a wonderful web site.

  19. Posted May 9, 2013 at 5:09 am | Permalink

    Thanks for helping me to obtain new ideas about pc’s. I also possess the belief that one of the best ways to keep your notebook computer in perfect condition is by using a hard plastic-type material case, or perhaps shell, that matches over the top of one’s computer.
    Most of these protective gear will be model unique since they
    are manufactured to fit perfectly across the natural casing.

    You can buy these directly from the seller, or through third
    party places if they are readily available for your mobile computer, however not all laptop will have a shell on the market.
    Yet again, thanks for your recommendations.

  20. Posted May 9, 2013 at 6:50 am | Permalink

    For hottest news you have to pay a quick visit world-wide-web and on world-wide-web
    I found this web page as a best web page for newest updates.

  21. Posted May 14, 2013 at 9:48 am | Permalink

    I have been browsing online more than 2 hours today, yet I never found any interesting article like yours.
    It’s pretty worth enough for me. In my view, if all website owners and bloggers made good content as you did, the web will be much more useful than ever before.|
    I couldn’t resist commenting. Well written!|
    I will right away clutch your rss feed as I can’t find your email subscription link or e-newsletter service. Do you have any? Kindly permit me recognize in order that I may just subscribe. Thanks.|
    It’s appropriate time to make some plans for the future and it’s time to be happy. I have read this post and if I could I want to suggest you some interesting things or tips. Perhaps you can write next articles referring to this article. I want to read more things about it!|
    It’s appropriate time to make a few plans for the future and it is time to be
    happy. I have learn this publish and if I could I wish to recommend you some fascinating issues or advice.
    Maybe you can write subsequent articles relating to this
    article. I want to learn even more things approximately it!
    |
    I have been browsing online greater than three hours as of late, yet I by no means found any attention-grabbing article like yours.

    It’s lovely value sufficient for me. In my opinion, if all web owners and bloggers made just right content material as you probably did, the net will probably be much more helpful than ever before.|
    Ahaa, its good discussion regarding this article here at this website, I have read all that, so at this time me also commenting here.|
    I am sure this article has touched all the internet visitors, its really really fastidious piece of writing on building up new web site.|
    Wow, this piece of writing is nice, my sister is analyzing these kinds of things, so I am going to convey her.|
    bookmarked!!, I really like your blog!|
    Way cool! Some very valid points! I appreciate you penning this post and also the rest of the website is also really good.|
    Hi, I do believe this is an excellent blog. I stumbledupon it ;) I will come back yet again since i have bookmarked it. Money and freedom is the best way to change, may you be rich and continue to guide other people.|
    Woah! I’m really loving the template/theme of this site.
    It’s simple, yet effective. A lot of times it’s tough
    to get that “perfect balance” between superb usability and visual appearance.
    I must say you have done a awesome job with this. Also, the blog loads super fast for me on Chrome.
    Exceptional Blog!|
    These are genuinely impressive ideas in about blogging. You have touched some good points here.
    Any way keep up wrinting.|
    Everyone loves what you guys tend to be up too. Such clever work and exposure!
    Keep up the great works guys I’ve incorporated you guys to blogroll.|
    Hey! Someone in my Myspace group shared this site with us so I came to take a look. I’m definitely
    loving the information. I’m bookmarking and will be tweeting this to my followers! Superb blog and wonderful design and style.|
    I enjoy what you guys tend to be up too. This type of clever work and reporting! Keep up the superb works guys I’ve included you guys to blogroll.
    |
    Hi there would you mind stating which blog platform you’re using? I’m going to start my own blog soon but I’m having a hard time deciding between BlogEngine/Wordpress/B2evolution and Drupal. The reason I ask is because your layout seems different then most blogs and I’m looking for something
    completely unique. P.S Apologies for getting off-topic
    but I had to ask!|
    Hello would you mind letting me know which web host
    you’re using? I’ve loaded your blog in 3 different web browsers
    and I must say this blog loads a lot quicker then most.
    Can you recommend a good web hosting provider
    at a reasonable price? Kudos, I appreciate it!|
    I love it when folks get together and share ideas. Great site, stick with it!
    |
    Thank you for the auspicious writeup. It in fact was a amusement
    account it. Look advanced to more added agreeable from you!
    However, how can we communicate?|
    Hi there just wanted to give you a quick heads up.
    The words in your article seem to be running off the screen in Ie.
    I’m not sure if this is a format issue or something to do with internet browser compatibility but I figured I’d post to let
    you know. The design and style look great though! Hope you
    get the issue fixed soon. Kudos|
    This is a topic that’s close to my heart… Many thanks! Exactly where are your contact details though?|
    It’s very simple to find out any topic on net as compared to textbooks, as I found
    this paragraph at this web site.|
    Does your website have a contact page? I’m having problems locating it but, I’d
    like to shoot you an e-mail. I’ve got some recommendations for your blog you might be interested in hearing. Either way, great website and I look forward to seeing it expand over time.|
    Hello! I’ve been reading your site for some time now and finally got the courage to go ahead and give you a
    shout out from Porter Texas! Just wanted to say keep up the excellent
    work!|
    Greetings from California! I’m bored to tears at work so I decided to browse your website on my iphone during lunch break. I really like the knowledge you present here and can’t wait to take a look when I get home.
    I’m shocked at how fast your blog loaded on my phone .. I’m
    not even using WIFI, just 3G .. Anyways, good blog!
    |
    Its like you read my thoughts! You seem to grasp a lot approximately this, like you wrote
    the book in it or something. I believe that you simply can
    do with a few % to power the message home a bit,
    but instead of that, this is magnificent blog. A fantastic read.
    I’ll certainly be back.|
    I visited many sites however the audio quality for audio songs present at this web site is actually superb.|
    Howdy, i read your blog from time to time and i own a similar one and i was just wondering if you get a lot of spam remarks? If so how do you stop it, any plugin or anything you can advise? I get so much lately it’s driving me mad so any help is very much appreciated.

    |
    Greetings! Very helpful advice within this article! It is the little changes which will make the most important
    changes. Thanks a lot for sharing!|
    I seriously love your blog.. Great colors & theme.
    Did you build this amazing site yourself? Please reply back as I’m planning to create my own personal website and would like to learn where you got this from or exactly what the theme is named. Thanks!|
    Hi there! This article could not be written any better! Looking through this post reminds me of my previous roommate! He continually kept preaching about this. I will send this information to him. Fairly certain he will have a very good read. Many thanks for sharing!|
    Amazing! This blog looks exactly like my old one! It’s on a totally different topic but it
    has pretty much the same layout and design. Superb choice of colors!
    |
    There’s certainly a lot to find out about this issue. I love all the points you have made.|
    You’ve made some decent points there. I checked on the
    web for more info about the issue and found most individuals will go along with your views on this web site.

    |
    What’s up, I log on to your new stuff regularly. Your humoristic style is witty, keep up the good work!|
    I simply could not go away your web site prior to suggesting that I extremely enjoyed the usual information an individual provide for your guests? Is going to be again regularly to inspect new posts|
    I want to to thank you for this great read!! I absolutely enjoyed every bit of it. I’ve got you bookmarked to check
    out new things you post…|
    Hello, just wanted to tell you, I enjoyed this article.

    It was helpful. Keep on posting!|
    I drop a leave a response whenever I like a article on a site or
    I have something to add to the discussion. Usually it’s triggered by the fire communicated in the post I looked at. And after this post Using Script tags to do remote HTTP calls in Javascript « Jay by Jay Fresh. I was moved enough to create a thought :-) I actually do have a few questions for you if it’s
    okay. Could it be simply me or do some of these
    remarks look as if they are left by brain dead individuals? :-P And, if you are posting at additional social sites, I would like to keep up
    with you. Would you list all of your community pages like your linkedin profile, Facebook page or twitter feed?

    Hi there, I enjoy reading through your article. I wanted
    to write a little comment to support you.
    I every time spent my half an hour to read this weblog’s articles or reviews every day along with a mug of coffee.
    I constantly emailed this weblog post page to all my contacts, as if like to read it next my links will too.
    My developer is trying to persuade me to move to .net from PHP. I have always disliked the idea because of the expenses. But he’s tryiong none the less.
    I’ve been using WordPress on several websites for about a year and am nervous about switching to another platform. I have heard very good things about blogengine.net. Is there a way I can import all my wordpress posts into it? Any kind of help would be really appreciated!
    Hello there! I could have sworn I’ve visited this site before but after looking at a
    few of the articles I realized it’s new to me. Anyways, I’m definitely pleased I found it and I’ll be book-marking it and checking back frequently!
    Wonderful article! This is the type of information that are supposed to be shared across the net. Shame on the search engines for now not positioning this publish upper! Come on over and visit my website . Thank you =)
    Heya i’m for the first time here. I found this board and I find It really useful & it helped
    me out a lot. I hope to give something back and help others like you helped me.

    Greetings, I think your blog could be having web browser compatibility issues.
    Whenever I take a look at your blog in Safari, it looks fine
    however, if opening in I.E., it’s got some overlapping issues. I just wanted to provide you with a quick heads up! Apart from that, wonderful blog!
    Somebody necessarily assist to make critically articles I would state. That is the very first time I frequented your website page and up to now? I amazed with the research you made to make this actual post extraordinary. Wonderful process!
    Heya i am for the primary time here. I found this board and I in finding It really helpful & it helped me out much. I’m hoping
    to give one thing back and help others such as you
    helped me.
    Hi there! I simply wish to give you a big thumbs up for the great info you have got here on
    this post. I am returning to your web site for more soon.

    I always used to study post in news papers but now as I am a
    user of internet therefore from now I am using net for articles
    or reviews, thanks to web.
    Your means of telling all in this paragraph is in
    fact good, every one can simply know it, Thanks a lot.

    Hello there, I discovered your blog via Google whilst searching for a similar
    matter, your website came up, it appears to be like great. I have bookmarked it in my google bookmarks
    Hello there, just was aware of your weblog via Google, and found that it is really informative.
    I’m gonna watch out for brussels. I’ll appreciate if you continue this in future.
    Numerous people will likely be benefited out of your writing.
    Cheers!
    I am curious to find out what blog system you have been working
    with? I’m having some minor security problems with my latest blog and I’d like to
    find something more risk-free. Do you have any solutions?

    I’m extremely impressed with your writing skills and also with the layout on your weblog. Is this a paid theme or did you customize it yourself? Either way keep up the excellent quality writing, it’s
    rare to see a nice blog like this one nowadays.

    I’m extremely impressed together with your writing abilities and also with the layout on your blog. Is that this a paid subject matter or did you customize it your self? Either way keep up the nice quality writing, it is rare to peer a great blog like this one these days..
    Hello, Neat post. There is an issue with your website in internet explorer, could check this? IE nonetheless is the marketplace chief and a good section of people will miss your excellent writing because of this problem.
    I am not sure where you’re getting your info, but great topic.
    I needs to spend some time learning much more or understanding
    more. Thanks for magnificent info I was looking for this info for my mission.

    Hi, i think that i saw you visited my website thus i came to
    “return the favor”.I am trying to find things to improve my site!

    I suppose its ok to use a few of your ideas!

  22. Posted May 15, 2013 at 11:30 pm | Permalink

    Stretch marks occur when the skin is stretched over a
    short period of time, such as during pregnancy or as a result of sudden growth spurts.
    While the essential oils are often considered
    the “active ingredients”, its important to consider the “carrier oils” are exceptionally therapeutic as well.
    Furthermore, it helps to prevent premature aging and reduces
    and prevents wrinkles.

  23. Posted May 15, 2013 at 11:51 pm | Permalink

    You need to take part in a contest for one of the greatest
    blogs online. I will recommend this site!


2 Trackbacks/Pingbacks

  1. Google gadgets

    So I’ve been messing around with various different widget frameworks on and off over the last few months as preparation for a workshop I’m going to be involved with. I started out with Yahoo Widgets (nĂ©e Konfabulator) mainly because the ex…

  2. [...] reasons. JSONP is a convention between the client and the server to bypass this restriction using script tag injection. More explanation here. It is this convention that allows us to call Yahoo Pipes directly from [...]

Post a Comment

Required fields are marked *
*
*

Follow

Get every new post delivered to your Inbox.