Cross-Domain calls using JavaScript in SharePoint Apps

Posted on 6/21/2013 @ 2:54 PM in #SharePoint by | Feedback | 8072 views

Sounds simple enough right? You’ve probably done $.ajax, and jsonp? Yeah all that doesn’t work in SharePoint. The main reason being, those calls need to work under the app’s credentials. So instead here is what a SharePoint app does,

  1. It downloads a file called ~hostweburl/_layouts/15/SPRequestExecutor.js.
  2. This file creates an IFrame in your page which then downloads a file called ~appweburl/_layouts/15/AppWebproxy.aspx
  3. Then all calls that look like the below, are routed via AppWebProxy and run on the server under the apps identity.
   1:  var executor = new SP.RequestExecutor(this.appweburl);
   2:  var url = this.appweburl + "/_api/SP.AppContextSite(@target)/web?" + "@target='" + this.hostweburl + "'";
   4:  executor.executeAsync({
   5:      url: url,
   6:      method: "GET",
   7:      headers: { "Accept": "application/json; odata=verbose" },
   8:      success: function (data) {
   9:          alert(data.body);
  10:          // var jsonObject = JSON.parse(data.body);
  11:      },
  12:      error: function (data, errorCode, errorMessage) {
  13:          alert(errorMessage);
  14:      }
  15:  });


The above code assumes that you have a hold of the appweburl and hostweburl properties. All this is detailed in my planet of the apps book.

The reason Microsoft choose this route is because

  1. All such calls execute under the apps identity
  2. Unregistered “apps” (i.e. spurious calls) can be detected and dropped
  3. And your app doesn’t have to deal with the complexity of jsonp etc. Everything just works!

This however, has a big problem! Provider hosted apps (i.e. the ones with no appweb) cannot make use of this?

Yeah seriously! But there is a workaround. What you do is, you provision a dummy AppWeb. You will never use it for anything, except to get a hold of the AppWebProxy.aspx. And provisioning an AppWeb will also give you {StandardTokens} (see app replacement tokens for more details.)

So, provider hosted apps can also use Cross-domain calls using JavaScript? Sure! (And this is also detailed out in my planet of the apps book).

But, there is a big gotcha with this approach .. which I am going to talk of in my next article.

Sound off but keep it civil:

Older comments..