JSONP and Backbone.js - javascript

I would like to use Backbone.js with a REST api I control. I was hoping to have the REST api and the Backbone scripts live on a different domain but unfortunately this will be blocked, as it is a cross domain request.
Does Backbone.js have an built in functionality to support JSONP requests? Or, alternatively, does anyone have any experience with manually adding JSONP support to Backbone.js sync system?

JSONP support for GET operations can be added via fetch's options.
In the same hash where you configure your success and error handlers, add an object like so:
{dataType: "jsonp"}
This will pass along the jsonp option to JQuery's ajax handler, and automagically, you'll have JSONP support for retrieving models / collections.

You will not be able to use your entire REST API with JSONP. You can only call GET requests with JSONP (it works by writing a new <script> tag on the current document, then calling a javascript callback...).
To use all HTTP verb (POST, DELETE, PUT), you can use the CORS protocol : http://www.w3.org/TR/access-control/.
CORS is a protocol negotiated between a browser and a web-service that tells the browser that it is “OK” to execute Javascript code from a cross-domain call
To use this, you just need to include some custom headers in your server response that tells the browser that it's ok to accept cross domain requests. Here's an blog post that explains how to implement it with RubyOnRails (but it should be quite similar with others framework...) : http://www.tsheffler.com/blog/?p=428
It's the simplest solution, you can use backbone.js as if you where on the same domain, and it works with most current browsers (Internet Explorer 8+, Firefox 3.5+, Safari 4+, and Chrome) !
If you need older browser support, I did manage to make backbone work using easyXDM :
easyXDM is a Javascript library that enables you as a developer to easily work around the limitation set in place by the Same Origin Policy, in turn making it easy to communicate and expose javascript API's across domain boundaries.
It's a little more complicated, and works with a some well known iframe hacks (that are sometimes used in javascript widgets like GMaps, facebook widgets, ...).
Hope this help!

Related

Is it possible to prevent an unknown javascript script from being able to make a network call in a browser?

If I'm loading arbitrary external javascript code in a browser setting, is it possible to ensure it can't make the browser run make any ajax calls or network requests?
Can you prevent any resource calls? - No. (haven't explored the 'extension' route though)
Since even an <img src='any valid url'> creates a resource request which your code cannot prevent.
Can you prevent ajax calls? - Yes, to an extent.
Assuming that you want to ensure that any third party libraries shouldn't make any arbitrary ajax calls (cross domain), you will simply ensure that you don't enable CORS in your web server.
Your own application code can make ajax calls since they are in your domain only. However, you can filter those calls on server to check for specific properties like purpose, credentials, etc
It may be worth exploring google caja (haven't tried that myself)

CORS in embedded javascript

I'm intending to add security for our Javascript code which gets embedded on other sites - eg: like analytics code.
The user copies 4-5 lines of the code and puts it on his site. The code actually downloads the real script as the next step.
I have been recommended to use CORS instead of the current JSONP calls as I can restrict the domains.
As I understand, the CORS would work only if the html page which will add my scripts needs to add access domains and if I add the access domains for the the js file, it wouldn't work.
Is the CORS for the final js or the html page intending to use my script?
Edit:
Since it's confusing to the users, I have made it more simple.
HTML in domain A adds my script from Domain B like Google analytics. Can I add access-domains: while rendering my JS or should the HTML add the access-domains in the response?
There is a good explanation from wiki for this question:
CORS can be used as a modern alternative to the JSONP pattern. While JSONP supports only the GET request method, CORS also supports other types of HTTP requests. Using CORS enables a web programmer to use regular XMLHttpRequest, which supports better error handling than JSONP. On the other hand, JSONP works on legacy browsers which predate CORS support. CORS is supported by most modern web browsers. Also, while JSONP can cause cross-site scripting (XSS) issues where the external site is compromised, CORS allows websites to manually parse responses to ensure security.
As I understand, the CORS would work only if the html page which will add my scripts needs to add access domains
You can access all domains via:
Access-Control-Allow-Origin: *
Also now CORS has good support.
P.S. IE8-9 has own imlementation by XDomainRequest.
CORS works by having your server output the Access-Control-Allow-Origin header containing the allowed domains. The sites that make ajax requests to your server don't need to do anything special to enable CORS, there is no configuration required. The sites just simply make normal XHR requests and the browser will internally handle the CORS.
You control the CORS access from the header on your server. In CORS, you can also control the HTTP verbs that are allowed, for example POST or GET (Access-Control-Allow-Methods) or the permitted request headers (Access-Control-Allow-Headers).
Note that IE8 doesn't support the CORS XHR, Microsoft decided to create their own CORS implementation with XDomainRequest. So if any of the sites that call your server want to support IE8, they will need to use XDomainRequest instead of XMLHttpRequest. There is no support for CORS in IE7 or eariler - not even XDomainRequest.

Why is cross domain AJAX prevented *if* you have no intention of evaluating the response as a script?

Let's say I want to use AJAX to retrieve a json file from an untrusted different domain.
I then parse the response as a javascript object without any script evaluation.
(A cookie is not sent with my request.)
I don't understand why the browser prevents me from doing this.
I understand that if I were to evaluate the response as a script then that would be a security issue.
I understand that there are work-arounds to achieve the above.
Is there a reason that my specific scenario should be prevented, or has it just got accidentally caught up in the same-origin dragnet?
Thanks.
(assuming the server does not support CORS)
... you have no intention of evaluating the response as a script?
Firstly, browser security has no way of determining what you intend to do.
Second, the same source / origin restrictions are designed prevent other things as well: e.g. see
http://blogs.msdn.com/b/ieinternals/archive/2009/08/28/explaining-same-origin-policy-part-1-deny-read.aspx
Cross-domain AJAX is possible, but the remote server needs to support CORS and there may be certain header restrictions.
JSONP is not necessary for most applications. If the remote server does not support CORS, then you're stuck with the same-origin garbage and you'll have to use JSONP.
Note:
Older browsers don't support CORS. You may want to use jQuery or a similar framework (I've had trouble with Mootools and cross-domain AJAX because I couldn't figure out how to remove some of the default headers. jQuery worked out of the box for me on my set-up.

Cross-Origin resource sharing and file://

I am writing an HTML5 application that is gathering data from a few different sources using JSONP. Anything I'm doing with a GET works perfectly. I'm now trying to POST data, and I've run into an interesting snag. I need to POST data from my application to another, where my application is running from a local machine. I am trying to write a cross-platform capable mobile application (think Pulse/Flipboard), so the code will always be running from a local source. My thought process was as follows:
Use JSONP - JSONP does not allow for posting, it just doesn't work that way (Post data to JsonP)
Rely on CORS - Since the request is coming from a local source using file://, the origin header is null. This causes the request to fail (XmlHttpRequest error: Origin null is not allowed by Access-Control-Allow-Origin)
Use another server to bounce the request off of - this would be expensive
All of the browsers I'm targeting are webkit based (iPad, Playbook, Android), so I'm wondering if there are any creaks in the same origin policy code that I can sneak through? Maybe something using iframe or postMessage?
As it would turn out, the easiest way to do this is to post to the target url inside of an iframe. Same origin policy on most browsers allows you to perform an HTTP POST from one domain to another unrelated domain. I solved the problem by adding an iframe to my page, initially set to a local bootstrapping page. Since that page was loaded from the same domain, I am able to control it via script. I used that to post the form to my target site, and polled the results to determine if my call was successful. It's not elegant, but it works.
This Javascript library can almost certainly help you:
http://easyxdm.net/
easyXDM is a Javascript library that
enables you as a developer to easily
work around the limitation set in
place by the Same Origin Policy, in
turn making it easy to communicate and
expose javascript API’s across domain
boundaries.
..
At the core easyXDM provides a
transport stack capable of passing
string based messages between two
windows, a consumer (the main
document) and a provider (a document
included using an iframe). It does
this by using one of several available
techniques, always selecting the most
efficient one for the current browser.
For all implementations the transport
stack offers bi-directionality,
reliability, queueing and
sender-verification.

how facebook does cross domain ajax call?

I am looking forward to create a javascript API that contains most of the functions that facebook Javascript API provides.
FB.api
FB.init
FB.logout
FB.getLoginStatus
FB.login
FB.ui
I can just embed script tag in remote website and need to do all the ajax calls from that page to my server. I am creating an architecture and needs someone help in finishing it with his/her excellent ideas.
Take a look at https://github.com/facebook/facebook-js-sdk/blob/deprecated/src/core/xd.js
They use a combination of rpc workarounds (with a relay file), Flash Local Connection and postMessage, whichever is supported by the browser.
You can also take a look at Cross Site XmlHttpRequest(CORS). From your question, it seems that you can control your server that will respond to the requests. In that case, you can tune the headers to receive requests and respond to cross domain requests.
Then, your embedded script will be able to talk to your server from any web page if you configure the request header in the requests that you make from your embedded script.
I like this method as it is extremely easy to implement. Watch out for browser support though!
They are using JSONP. It's widely used and is supported by javascript frameworks like JQuery.

Categories