Ajax Bestiary: A Javascript Field Guide
 
Ajax Bestiary: A Javascript Field Guide
 
 

Cross Site Scripting – the new old way

Posted by Dave Mahon

Cross Site Scripting (XSS) is a big security no-no. It’s never supposed to happen, because as we all know, any script operating within your page has full access to the entire DOM of the page.

Then again, there is so much functionality that we want to implement without reinventing the wheel. Marketing departments want to use third-party tracking tools. The IT folks want to distribute the load for our network heavy site across the third-level domains www.domain.com, static.domain.com and data.domain.com. And users want more functionality than we can hope to provide on our own.

So resigned to the reality that XSS is a legitimate necessity, we need a way to do it. The old way (as far back as the mid-90’s, in fact) was straightforward:

document.write(<script language=”JavaScript” type=”text/javascript” src=”http://data.domain.com/myscript.js”></script>’);

This is of course problematic as it treats DOM nodes improperly and may not even get processed by modern browsers. Instead, jQuery provides access to JSONP which will do the same thing – insert a new script node in the DOM – but do it in an XHTML compliant way.

Accessing JSONP is pretty straightforward:

$.getJSON("http://data.domain.com/myscript&callback=?”, inPageFunction);

The key bit is &callback=? – this causes jQuery to insert a script node into the DOM, which is then immediately executed and returned to the callback function, inPageFunction, like so:

inPageFunction({data:"foo";})

If you forget &callback=? you’ll get the error Access to restricted URI denied. And yes, since we’re inserting a script node, we’re limited to GET requests. And if the call fails, you’ll simply get nothing back – no useful error messages.

Further, the next generation of browsers is coming out with integrated support for cross site XMLHttpRequest, but since when have we not had to code to support multiple versions of browsers?

There are loads of good guides to expand your knowledge:


10 Comments

Leave a Reply