In this blog I would like to share code to get the content type collection from APP host web in SharePoint Hosted app using JavaScript Object Model.
- var ctx;
- var appCtxSite;
- var contentTypeCollection;
- var contentType;
- var hostWebURL;
- var appWebURL;
- var contentTypeName;
- var ContentTypeID;`
- var ContentTypeEnumerator;
- $(document).ready(function () {
- // debugger;
- //// Get the URI decoded URLs.
- hostWebUrl = decodeURIComponent(manageQueryStringParameter('SPHostUrl'));
- appWebUrl = decodeURIComponent(manageQueryStringParameter('SPAppWebUrl'));
- //calling the getHostWeb method in ready function to get content type on when page is ready
- getHostWeb();
- });
- //This function is used to get the hostweb url
- function manageQueryStringParameter(paramToRetrieve)
- {
- var params = document.URL.split("?")[1].split("&");
- var strParams = "";
- for (var i = 0; i < params.length; i = i + 1)
- {
- var singleParam = params[i].split("=");
- if (singleParam[0] == paramToRetrieve)
- {
- return singleParam[1];
- }
- }
- }
- //get the list data from host web
- function getHostWeb()
- {
- //get current app web context
- ctx = new SP.ClientContext(appWebUrl);
- //get current host web context
- appCtxSite = new SP.AppContextSite(ctx, hostWebUrl);
- //get current host web
- if (ctx != undefined && ctx != null)
- {
- web = appCtxSite.get_web();
- }
- //// .load() tells CSOM to load the properties of this object
- ctx.load(web);
- ctx.executeQueryAsync(getContentTypeCollection, onQueryFailed);
- }
- function getContentTypeCollection()
- {
- //Get all content types from current app host web
- contentTypeCollection = web.get_contentTypes();
- //load the content type collection
- ctx.load(contentTypeCollection);
- ctx.executeQueryAsync(getallContentType, onQueryFailed);
- }
- function getallContentType()
- {
- ContentTypeEnumerator = contentTypeCollection.getEnumerator();
- var count = contentTypeCollection.get_count();
- if (count > 0)
- {
- //Get content type one by one
- while (ContentTypeEnumerator.moveNext())
- {
- contentType = ContentTypeEnumerator.get_current();
- contentTypeName = contentType.get_name();
- alert(contentTypeName);
- }
- }
- }
- function onQueryFailed(sender, args)
- {
- alert('Request failed. ' + args.get_message() + '\n' + args.get_stackTrace());
- }
In this blog we have explored how to get the all content types from SharePoint Hosted web using JavaScript Object Model.
Happy Coding

Join the conversation! Your thoughts help the community grow.