I read a nice write up on on JSON and JSONP by Angus Croll. He provided a sample implementation of a safe JSONP library.
The library is concise and does the trick for a single connection, but I found it didn’t handle multiple connections. It would overwrite a single global callback, so if you had connections of varying speeds, you would undoubtedly get errors. For instance, “Request 1” is very slow, and “Request 2” gets finished before it. When “Request 1” gets finished, it uses the callback for “Request 2”. This actually happened the first time I loaded it up and ran it. Not good.
Here is a simple updated version that takes care of that particular problem.
To test it out:
If you are really worried about multiple global objects JSONPCallback_1, JSONPCallback_2, etc - you could store them all in an array instead. Like this:
The only but main problem is that you’re still open for “attacks”. This is because you can’t fix the problem of remote script execution with jsonp as it stands. The proper fix is using CORS, but in that case you’re left to the mercy of the other party. If they won’t allow CORS (but do intend to distribute data through jsonp), your only option is unsafe jsonp. My proposal (at http://qfox.nl/weblog/216 ) tries to address that part. Have the browser fetch the jsonp and return a json to your callback. That’s pretty much the only way to get things safe (assuming json is safe, of course).
I agree about still being open for attacks. That is an unfortunate side effect of loading a script from another domain (one you don’t control).
With your proposal, it seems you are not even adding a script to the page, instead you are having the browsers implement a loadJsonp() function that ignores the same origin policy. That is fine, but I’m not sure you could still call it JSONP at that point. JSONP implies loading a script tag, exploiting the fact that a script doesn’t abide by the same origin policy.
Your site says that your proposal does not introduce anything new, but it couldn’t be implemented today without new functionality being introduced by browser vendors, right? Moving forward, a proposal like yours or the http://json-p.org will be a great change for the better for security concerns.