You have another question strikingly similar to this one open right now, but that one is primarily about AppWeb vs HostWeb differences -- so I'll tack an answer on here too:
Important pre-requisite: your app needs to ask for permission to read information from the host web:
In Napa, you'll find these settings by clicking the wrench icon (for project properties) on the left-hand navigation menu, then selecting "Permissions" -- make sure your app is at least asking for "Read" access on the "Web"
The MSDN example you've referenced should almost get you there, but you either need to add the getQueryStringParameter
function from somewhere (you can probably find it in some examples at OfficeDev/PnP -- or, a better option, is to use SP.ScriptHelpers.getDocumentQueryPairs()
to retrieve the QueryString values from the current page.
$(document).ready(function () {
var qsVals = SP.ScriptHelpers.getDocumentQueryPairs();
var hostWebUrl = decodeURIComponent(qsVals.SPHostUrl);
// note1
var clientContext = SP.ClientContext.get_current();
// note2
var appContextSite = new SP.AppContextSite(clientContext, hostWebUrl);
var hostWeb = appContextSite.get_web();
// note3
clientContext.load(hostWeb);
clientContext.executeQueryAsync(function() {
// do stuff with the objects you loaded in the host web
alert("Host web title: \n" + hostWeb.get_title());
}, function(sender, args) {
// something went wrong
console.log(args.get_message());
});
});
Note 1: You can just use SP.ClientContext.get_current()
here since you are working from the script that is on a page in the AppWeb.
Note 2: The SP.ProxyWebRequestExecutorFactory
seems unnecessary in my experience - despite the fact that many of the examples use this pattern. Additional note here, SP.ClientContext.get_current()
returns an instance of an already existing client context, so you do not use the new
keyword. We're creating an SP.AppContextSite
from nothing, so we do use the new
keyword.
Note 3: You load the client objects with the App Web Context (the one we obtained with get_current()
even though you navigate to the object from the appContextSite
(the one we got from new SP.AppContextSite()
.
Copying and pasting the entire code snippet into your browser dev tools (firebug, chrome js console, etc.) should give you an alert with the title of your host web.
The App model can take a while to get used to, take some time to check out blog posts out there and watch some videos on http://www.microsoftvirtualacademy.com/ and http://dev.office.com/training
getQueryStringParameter
?