SharePoint JavaScript Extensions


I’ve just released an alpha of a set of extensions for SharePoint 2010 that should prove very handy for simple applications. Additionally it is 100% sandbox friendly!

http://sp2010ext.codeplex.com/releases/view/80242 to track and download new releases as they are ready :)

/*
* Drag and drop file upload for SharePoint 2010
* SharePoint Client Object Model javascript wrapper
* Improved Browser support for Chrome and the SP ribbon
* Print page region
*
* By: Maarten Sundman - January 2012
* Version 0.1.0
* Features:
* Allows drag/drop upload of multiple files in to a sharepoint library
* Specifying client context
* Chrome compatibility fixes
* Query String parser
* Get List ID's for list operations
* Query list's * Get library folder
* SharePoint modal popup's
* Printing
* Note: Make sure sp.js and jquery are loaded before this if executing during page load   - ExcuteOrDelayUntilScriptLoaded
*/

/* CHROME AND IPAD SUPPORT */
//replace var _fV4UI = true within the master page with this function
function WebKitHandler()
{
	if($.browser.webkit || $.browser.safari)
	{
		//handle scrolling on less supported browsers like chrome 
		//once web parts complete loading they reload the default ribbon behavior so you get normal sharepoint style scrolling.
		//This bypasses the bug in webkit that causing nested scrolling to fail if the page has no height/scrolling at render time
		$('BODY').css("overflow","auto");
		var h = $('#s4-workspace').height();
		$('#s4-workspace').css("height", "auto").css("overflow-y", "auto").css("min-height", h);
	}
	else
	{
		//handle normal ribbon rendering and behavior on fully supported browsers
		//default ribbon behavior from the start
		var _fV4UI = true;
	}
}

/* END CHROME AND IPAD SUPPORT */
function LoadDragDropUpload()
{
	var browser = $.browser;
	if(browser.msie)
	{
		//handle lower capable browsers - aka IE 
		AddSilverlightHandler(); //silverlight control requires no additional work besides adding the event handler/html to display it on the page dynamically
	}
	else
	{
		//handle highly capable browsers
		if(browser.mozilla && browser.ua.version.slice(0,3) == "2.0")
	{
		//handle older versions of firefox which do not support drag/drop html5
		AddSilverlightHandler();
	}
		AddHTML5Handler();
	}
}

/* START GLOBALS */
//store client context - defaults at load to current context so is always available to use locally
var ctx = new SP.ClientContext.get_current();
//store list id
var listid = "";
//store SP.List
var list;
//store folder reference for uploading
var currentfolder = "";
//store results
var ResultItems;
//store fields to display
var ItemFields;
//store reference to element to write result table too, note it is expected to be a jQuery element reference
var DisplayID;

/* END GLOBALS */

/* START DRAG DROP UPLOAD */
//adds html and event bindings for handling silverlight drag and drop upload
function AddSilverlightHandler()
{
	$('table.ms-addnew').append("Upload Files");
	AddSilverlightHtml(GenerateUploadQueryString());
	$('#dropArea').bind('click', function()
	{
		$('#uploadBox')fadeIn("fast");
	});
}

//this function is incomplete do not use yet 
function AddHTML5Handler()
{
	
}

//TODO 
function UploadFile(file)
{
}

//generates querystring for loading the silverlight multiple upload control
function GenerateUploadQueryString()
{
	if(listid == "" && listid != "Error")
	{
		listid = GetCurrentListID();
	}
	if(currentfolder == "" && currentfolder != "Error")
	{
		GetRootFolder();
	}
	//?List=GUID&RootFolder=/Server/Relative/Path&MultipleUpload=1&IsDlg=1
	var querystring = "/_layouts/Upload.aspx?List={" + listid + "}&RootFolder=" + currentfolder + "&MultipleUpload=1&IsDlg=1";
	return querystring;
}

//TODO
function Html5DropHtml(QueryStringParams)
{
//todo: create web service for handling the file send, the javascript client OM unlike the silverlight one does not support file add
}

//builds HTML for the silverlight multiple upload control
function AddSilverlightHtml(QueryStringParams)
{
	var html = "
 + QueryStringParams + " scrolling='no' style='min-height:275px; width:100%; height:100%' frameborder='0'/>

"
	$("#dropArea").append(html);
}

/* END DRAG DROP UPLOAD */

/* START HELPERS */
//get ID of a specific list based on the loaded context
function GetListID(ListName)
{
	list = ctx.get_web().get_lists().getByTitle(ListName);
	//load list along with it's GUID and Title
	ctx.load(list, 'Title', 'Id', 'RootFolder');
	ctx.executeQueryAsync(Function.createDelegate(this,this.RetrievedListID), Function.createDelegate(this, this.ExecutionFailed));
}

//response handler
function RetrievedListID(sender, args)
{
	currentfolder = this.list.get_rootFolder();
	listid = this.list.get_id();
	return this.list.get_id();
}

//error handler - generic
function ExecutionFailed(sender, args)
{
	currentfolder = "Error";
	listid = "Error";
	return args.get_message();
}

//set's the current context to a specific URL
function SetContext(URL)
{
	ctx = new SP.ClientContext(URL);
}

//get's root folder of library
function GetRootFolder()
{
	currentfolder = GetQSParameterByName('RootFolder');
	if(currentfolder == "")
	{
		listid = GetCurrentListID();
	}
	while(currentfolder == "")
	{
		//wait for query to complete
	}
	return currentfolder;
}

//get the value of a specific query string parameter, returns "" if QS param is not present
function GetQSParameterByName(name)
{
	name = name.replace(/[[]/, "\[").replace(/[]]/, "\]");
	var regexS = "[\?&]" + name + "=([^&#]*)";
	var regex = new RegExp(regexS);
	var results = regex.exec(window.location.href);
	if(results == null)
	{
		return "";
	}
	else
	{
		return decodeURIComponent(results[1].replace(/+/g, " "));
	}
}

//gets server relative url of the specified client context
function GetWebUrl(context)
{
	return context.get_web().get_serverRelativeUrl();
}

//get id of list currently selected on screen
function GetCurrentListID()
{
	listid = SP.ListOperation.Select.getSelectedList();
	list = ctx.get_web().get_lists().getById(listid);
	ctx.load(list, 'Title', 'Id', 'RootFolder');
	ctx.executeQueryAsync(Function.createDelegate(this,this.RetrievedListID), Function.createDelegate(this, this.ExecutionFailed));
	return listid;
}
/* END HELPERS */

/* START PRINT PAGE REGION */
function LoadPrintView(sender) {
    var PrintingHTML = 'nn';
    PrintingHTML += $('HEAD').html();
    //PrintingHTML += ''; - Load print specific CSS if needed, or any other changes to how it should be displayed
    PrintingHTML += ''; PrintingHTML += sender.innerHtml; PrintingHTML += '';
	//write html to a hidden print window
    var printWindow = window.open('', '_blank', 'width=720,height=600');
    printWindow.document.open();
    printWindow.document.write(PrintingHTML);
    printWindow.document.close();
	//load print dialog
    printWindow.focus();
    printWindow.print();
	//auto close the hidden print window
    printWindow.close();
}
/* END PRINT PAGE REGION */

/* START EASY POPUPS */
function RefreshPageFromPopup(dialogResult, returnValue) {
    SP.UI.ModalDialog.RefreshPage(SP.UI.DialogResult.OK);
}

function SPPopupNoRefresh(url, height, width, title) {
    var options = SP.UI.$create_DialogOptions();
    options.url = url;
    options.height = height;
    options.width = width;
    options.AllowMaximize = true;
    options.title = title;
    SP.UI.ModalDialog.showModalDialog(options);
}

function SPPopupRefresh(url, height, width, title) {
    var options = SP.UI.$create_DialogOptions();
    options.url = url;
    options.height = height;
    options.width = width;
    options.AllowMaximize = true;
    options.title = title;
    options.dialogReturnValueCallback = RefreshPageFromPopup;
    SP.UI.ModalDialog.showModalDialog(options);
}

/* END EASY POPUPS */

/* START QUERY LISTS */

//query list on current web
function QueryLocalList(ListName, CAMLQuery, Fields) {
    ctx = new SP.ClientContext.get_current();
	ItemFields = Fields;
    var list = ctx.get_web().get_lists().getByTitle(ListName);
    var query = new SP.CamlQuery();
    query.set_viewXml(CAMLQuery);
    ResultItems = list.getItems(query);
    ctx.load(ResultItems, Fields);
    ctx.executeQueryAsync(Function.createDelegate(this, QueryListSuccess), Function.createDelegate(this, ExecutionFailed));
}

//query list on non-current spweb
function QueryRemoteList(ListName, CAMLQuery, Fields, Context) {
	ItemFields = Fields;
    var list = ctx.get_web().get_lists().getByTitle(ListName);
    var query = new SP.CamlQuery();
    query.set_viewXml(CAMLQuery);
    ResultItems = list.getItems(query);
    ctx.load(ResultItems, Fields);
    ctx.executeQueryAsync(Function.createDelegate(this, QueryListSuccess), Function.createDelegate(this, ExecutionFailed));
}

//display results as a table
function QueryListSuccess(sender, args) {
	var iEnum = ResultItems.getEnumerator();
	var resultTable = "
â + listItem.get_item(f) + ââ; } resultTable += ââ; } resultTable += ââ; //display results in the specified element DisplayID.append(resultTable); } 
/* END QUERY LISTS */

  1. No comments yet.
(will not be published)


%d bloggers like this: