Warning: SetCookie changes implementation in SharePoint 2013

I was recently working on verifying some of my custom code worked in SharePoint 2013.  I had some older code where I needed to set cookies and use them to remember user preferences.  I was debugging my code and I noticed that all of my cookies were coming back either true or false instead of the value I put into them.  I had been using a SharePoint JavaScript method called SetCookie.  Below is the implementation that has existed in SharePoint for the previous 3 versions (2003, 2007, and 2010).

function SetCookie(name, value, path)
{
	document.cookie=name+"="+value+";path="+path;
}

But for some reason Microsoft decided to change the implementation of this method in SharePoint 2013 to the following:

function SetCookie(sName, value) {
    SetCookieEx(sName, value, false, window);
}
function SetCookieEx(sName, value, isGlobal, wnd) {
    var c = sName + (value ? "=true" : "=false");
    var p = isGlobal ? ";path=/" : "";

    wnd.document.cookie = c + p;
}

Notice this new method tries to evaluate the value into a boolean and then forcefully sets the cookie to true or false.  So if you were storing anything other than boolean values in your cookies and used this method in previous versions of SharePoint, you will now need to update your code.  For this you have two options:

Option 1:  I found there is another method in SharePoint 2013 which still implements the SetCookie the same was as previous versions of SharePoint.

function SetMtgCookie(cookieName, value, path) {
    document.cookie = cookieName + "=" + value + ";path=" + path;

}

So you can easily do a search and replace for SetCookie to be replaced with SetMtgCookie and you’ll be good to go.

Option 2:  This is the option I opted for.  I decided that as tempting as doing a quick search and replace like I suggested in option 1 sounded, I wanted to remove my dependency on SharePoint’s implementation in case it changes again in the future.  Since the older SetCookie is only one line, I just replaced my method call to that line:

document.cookie=name+"="+value+";path="+path;

It was a pretty simple change, only slightly more time taken than option 1 and I removed a dependency.

Anyway, I hope this helps someone else out when troubleshooting code migration to SharePoint 2013.

One thought on “Warning: SetCookie changes implementation in SharePoint 2013

  1. Thanks! This works great, and it sets a Session cookie. Any suggestions for a more persistent cookie with an expiration date? Or I should just append the regular expire string?

Leave a Reply

Your email address will not be published. Required fields are marked *

*

*