So you’re writing a cool AJAXified mashup, grabbing data from various APIs and munging it together in the browser? If you’re seeing this Firefox error in Firebug, you want to read the rest of the article:
uncaught exception: Access to restricted URI denied (NS_ERROR_DOM_BAD_URI)
You’ll see similar errors in Opera and Safari, whilst Internet Explorer will happily service the request.
What Causes NS_ERROR_DOM_BAD_URI?
The exception gets raised when you send a HTTP GET requested to a different domain via an XMLHttpRequest object.
This restriction is called the Same Origin Policy and it’s generally a very good thingTM as it makes our browsers much more secure. It does cause headaches for those of us working with JSON over XMLHttpRequest but don’t worry, help is at hand.
How To Fix NS_ERROR_DOM_BAD_URI?
You can install a proxy at www.mydomain.com to get the data and send it on to your page but this is an incredibly bad idea:
- The security implications are manifold
- It slows down data load
- It increases server bandwidth
A much better solution is to programmatically add a new
<script> tag into the page’s header to load your data.
You can do this with a bit of code like this:
var script = document.createElement('script'); script.setAttribute('src', 'http://www.anotherdomain/api/stuff.json'); document.getElementsByTagName('head').appendChild(script);
Or you could use jQuery’s JSONP to do the hard work for you.
callback parameter (in some cases it’s called
json_callback). Thankfully there are a lot of APIs that do this.
JSON APIs That Support Callbacks
Music mashup authors will be pleased to note that Last.fm definitely provides callback support.
There are lots more APIs that support JSON callbacks, have a loook through the excellent documentation at Programmable Web to get some ideas.
API Providers, Please Support Callbacks
JSON callbacks are fast becoming standard practice, so if you’re writing an API that supports JSON, I recommend adding callback support. It’s not a difficult thing to add but it can make a massive difference to mashup authors.
Creative Common licensed photo by Dmitry Baranovskiy.