Common code requirements in SharePoint Javascript Object Model

Common code requirements in SharePoint Javascript Object Model
7 votes, 3.86 avg. rating (78% score)

Introduction

In this post we will check some common codes used in SharePoint JavaScript Object Model.
The post includes

  • Getting current site object
  • Getting current web object
  • Getting current web full url
  • Getting current list name and id
  • Getting current list selected items

Skill Level – Medium

Common Utility Codes

var context = SP.ClientContext.get_current();
this.site = context.get_site();		// Current Site Object
this.web	 = context.get_web();		// Current Web Object
context.load(this.site);
context.load(this.web);
context.executeQueryAsync(
	Function.createDelegate(this, this.onQuerySucceeded),
   
);

function onQuerySucceeded() 
{
	var lstGuid = SP.ListOperation.Selection.getSelectedList();  // List GUID of the current list
	var listname = "";		// if the List GUID is null try getting the List Name
	if (lstGuid == null) {
		listname = $(".s4-titletext h2 a:first").html(); //requires JQuery to get list name from ribbon breadcrumb
	}

   
	var items = SP.ListOperation.Selection.getSelectedItems();  // get selected items of the list
	var itemCount = CountDictionary(items);  // get selected items count

	//Get Current Web Full Url
	var webFullUrl = "";
	if (site.get_serverRelativeUrl() == "/") {
		webFullUrl = site.get_url() + web.get_serverRelativeUrl();
	}
	else {
		webFullUrl = site.get_url().replace(site.get_serverRelativeUrl(), web.get_serverRelativeUrl());
	}

}


Conclusion

Using common objects from JavaScript Object Model is not straight forward sometimes and tend to do some work arounds. Hope the code helps.

August 11, 2013 В· Adi В· No Comments
Tags: , , , ,  В· Posted in: Client Object Model, JavaScript Object Model, Sharepoint 2010, SharePoint 2013

Leave a Reply

What is 10 + 8 ?
Please leave these two fields as-is:
IMPORTANT! To be able to proceed, you need to solve the following simple math (so we know that you are a human) :-)