If you are reading this, I guess you are familiar with this error message

This is of course the same origin policy that prevents you being able to access jSon data that is stored on a different domain than your javaScript Code. This is really annoying if you are trying to use publicly hosted data, but there are ways round it

What is jSonP

In simple terms, this is when you pass a callback function name to the data provider server. This causes the data provider to wrap its jSon reponse up in a call to your function, as an argument. So lets say you do this, in this case using jQuery
If the server at ‘url’ knows how to react to a jsonp request, it will return something like,
yourfunction (returnedJson), and your function can then process the returned jSon.

What if you don’t have a server

But what if the data is not being hosted on a server (let’s say on dropbox or some other file sharing place), or what  if the data hosting  server doesn’t allow jSonp? You’re pretty much screwed.

Using Google Apps Content service as jSONP wrapper.

UrlFetch() in Google Apps Script is not subject to the same Same origin Policy as javaScript, so what if we passed the url holding the data to Google Apps Script as a parameter, asked it to do the data retrieval , wrap it up in a jSonp return, and then use google content service to serve the retrieved data back?
It works! I stumbled across this when I was researching ScriptDB as image store.
All you need to do is to create a publicly published google apps script that will accept a url and a callback, and wrap up the returned data in jSONP. I’ve already made one, here it is.
You can use it by referencing this URL (the code is here ).
and appending 2 arguments
  • url = encoded URI of the cross origin domain
  • callback = your callback function
What you’ll get back is

Example jquery script

Here’s an example of  picking up this json  file hosted using jQuery.
That gives this result


Using this technique, all that Cross Domain data hosting problems just go away. Here’s what you need
  • The  jsonP proxy.  The proxyUrl pointing to the google apps script proxy.
  • Provide the url and callback as parameters to the jQuery  getJSON function
  • Check returned data for an error code in your jsonp callback, or process your data

For the sake of the example, I have used jQuery but you should be able to use Ajax, plain javaScript or some other frameworks that support jSonP.  For more like this see From VBA to Google Apps Script.   Join our forum, follow the blog or follow me on twitter to ensure you get updates when they are available.

Much of  the code referred to here is the mcpher library.  You can find out how to include it in your project here.

For help and more information join our community,  follow the blog, or  follow me on Twitter