5

Since you can't apply custom headers on JSONP calls, how do I make cross domain requests AND apply custom headers using jQuery?

I'm basically trying to access google docs with jQuery and need to pass an authentication token:

var token = "my-auth-token";
$.ajax({
  url: "http://docs.google.com/feeds/documents/private/full?max-results=1&alt=json",
  dataType: 'json',
  beforeSend: function(xhr) {
    xhr.setRequestHeader("Authorization", "GoogleLogin auth=" + token);
  },
  success: function(data, textStatus, XMLHttpRequest) {
  },
  error: function(XMLHttpRequest, textStatus, errorThrown) {
  }
});

Note: The goal of this is to completely bypass the application layer. It's simple to use ruby to connect to the Google Data API, but it takes up a lot of resources parsing feeds all the time server-side.

Community
  • 1
  • 1
Lance Pollard
  • 66,757
  • 77
  • 237
  • 416
  • 3
    You can't, for the same reason as you can't do the same type of request to `myBank.com` which would either get my info or lock my account out, either one is very undesirable...and exactly why cross-domain requests like this aren't allowed. – Nick Craver Jun 18 '10 at 22:08

3 Answers3

5

You can use Google's JavaScript client library to query the Docs API. Although it doesn't come with helpers for Docs specifically, it can still be used with most APIs, including Docs. See this blog post by a Google employee that shows a working example.

If you end up in an infinite loop of authorizations, see this related question from Google groups. Basically, the cookies aren't getting set fast enough, so when the JavaScript client library checks, it finds nothing and redirects to the OAuth authorization page. A solution is to either add a small delay before the check is done, or use a login button that initiates the authorization instead of doing it on page load.

You would also need to add any image to your page that resides on the same domain. It can be hidden with CSS, as long as in the DOM.

Using the example in the above blog post, I was able to retrieve my documents list with JavaScript alone. Here's the modified initialize function I used to get rid of the infinite authorization loop:

function initialize() {
    var scope = 'http://docs.google.com/feeds/';

    if (google.accounts.user.checkLogin(scope)) {
        var service = new google.gdata.client.GoogleService('writely', 'DocList-App-v1.0');   
        service.getFeed(scope + 'documents/private/full/', handleFeed, handleError);  
    } else {
        var loginButton = $("<button>Click here to login</button>");
        loginButton.click(function() {
            var token = google.accounts.user.login(scope); // can ignore returned token  
        });
        $("body").append(loginButton);
    }
};  
​
Anurag
  • 132,806
  • 34
  • 214
  • 257
  • Almost there! Now I'm getting this error at the call `service.getFeed`: "Uncaught Error: An image of the same domain is required on this page for authenticated reads and all writes." Any ideas??? – Lance Pollard Jun 19 '10 at 01:32
  • 1
    @viatropos - You're almost there. Put any image on the page, but it must reside on the same domain. For example, I put this temp image on the page and hid it with stylesheets - ``. – Anurag Jun 19 '10 at 01:39
  • AWESOME! This is exactly what I was looking for, thanks a lot Anurag. – Lance Pollard Jun 19 '10 at 01:39
3

Consider to write some code at the server side which plays for a proxy and let jQuery call it.

BalusC
  • 992,635
  • 352
  • 3,478
  • 3,452
  • You can. Cross-domain XHR is supported in many newer versions of browsers, including IE8. – Eli Grey Jun 19 '10 at 01:07
  • @Eli - No, you can't, not the way the OP originally had...it's not a matter of "supporting it," it's the exact opposite, they're *actively preventing* it, as a security measure. – Nick Craver Jun 19 '10 at 02:11
  • @Eli: I updated the answer to remove the "you can't". I'd appreciate if you correct the downvote. – BalusC Jun 19 '10 at 02:47
  • Fixed. @Nick: I was just answering the asker's question with something that would work, if he could get Google to support it. – Eli Grey Jun 19 '10 at 13:07
0

You can, as long as the external domain allows it by sending an appropriate Access-Control-Allow-Origin header. Then just use the XMLHttpRequest API in browsers that support the standard cross-domain XHR API and XDomainRequest in IE.

Eli Grey
  • 32,712
  • 13
  • 69
  • 92