Context information is passed to the SharePoint-hosted app on the query string. One of these query string parameters, SPHostUrl, is the URL to the host web. You can get the value of this parameter using the built-in function GetUrlKeyValue.
var hostUrl = GetUrlKeyValue("SPHostUrl");
The URL to the app web is also passed on query string as a parameter named SPAppWebUrl. This means you have two ways to get the URL to the app web: using the technique shown above or using properties of the _spPageContextInfo object.
var appUrl = GetUrlKeyValue("SPAppWebUrl");
var appUrl = _spPageContextInfo.webAbsoluteUrl;
Here's an example of how to use these values to get data from the host web in code running in the app web. Please note that to make this call you must request the appropriate permissions (e.g. Web.Read) in the app manifest.
function callToHostWeb() {
var appUrl = GetUrlKeyValue("SPAppWebUrl");
var hostUrl = GetUrlKeyValue("SPHostUrl");
var url = appUrl + "/_api/SP.AppContextSite(@target)" +
"/Web/Lists/getByTitle('Products')/Items?" +
"$select=Title&$top=15&@target='" + hostUrl + "'";
var call = jQuery.ajax({
url: url,
type: "GET",
dataType: "json",
headers: {
Accept: "application/json;odata=verbose"
}
});
call.done(function (data, textStatus, jqXHR) {
var message = jQuery("#message");
message.text("First 15 products in the host web list:");
message.append("<br/>");
jQuery.each(data.d.results, function (index, value) {
message.append(value.Title);
message.append("<br/>");
});
});
call.fail(failHandler);
}