RSS

Some useful Javascript variables/functions in Sharepoint

12 Jan

Here is a list of some useful Javascript variables/functions that I collected from many articles online. I have tested all these variables/functions in SharePoint 2010. All these are available Out-Of-The-Box, you don’t need to add any javascript libraries.

1. _spUserId (Variable)

This variable gives the ID of the logged in user. For an anonymous user, this variable will be empty.


var uid = _spUserId;

You can test this variable in the address bar of your browser. Try


javascript:alert(_spUserId);

You will see an alert message with the ID of the logged in user.

2. JSRequest (Object)

Using this JSRequest object, we can get the querystring, pathname and filename. Before using any of these properties, you should call JSRequest.EnsureSetup();

Ex: page url is http://www.xyz.com?qid=15

To get a querystring value


JSRequest.EnsureSetup();
var q = JSRequest.QueryString["qid"]; // q = 15

Similarly, you can use


JSRequest.EnsureSetup();
var f = JSRequest.FileName; // current page name
var p = JSRequest.PathName; // server relative url

3. GetUrlKeyValue(parameter, noDecode, url) (Method)

GetUrlKeyValue() is a javascript function using which we can get the Query string parameter either from url in the browser or a url that we specify.

parameter(string): query string parameter from the url.

noDecode(bool): specifies whether the value has to be encoded or not. If false value is decoded, else returned as it is.(Optional)

url(string): the url from which Query string values are to be retrieved.(Optional)

Ex:

alert(GetUrlKeyValue('a', false, 'www.xyz.com?a=te%20st'));

The above statement will return the value ‘te st’. Here we are specifying our own url.

alert(GetUrlKeyValue('a', false));

The above statement will look for a query string variable ‘a’ in the browser url, and returns the decoded value.


alert(GetUrlKeyValue('a'));

The above statement will look for a query string variable ‘a’ in the browser url.

4. _spPageContextInfo (Object)

_spPageContextInfo object has several useful properties, some are

a. webServerRelativeUrl (for current web)
b. siteServerRelativeUrl (current site collection url)
c. webLanguage (for localization)
d. currentLanguage (for localization again)
e. webUIVersion
f. userId (current user id just like _spUserId)
g. alertsEnabled (more for current page if it has any alerts on it)
h. allowSilverlightPrompt (to have that prompt or not on the page)
i. pageItemId
j. pageListId (Guid)

We can get the webServerRelativeUrl simply by saying


var url = _spPageContextInfo.webServerRelativeUrl;

All the remaining object properties can be used in the same way.

5. escapeProperly(str) (Method)

This function returns the URL encoded value of a given string.


var s = escapeProperly("hello world!!"); //s = "hello%20world%21%21"

6. unescapeProperly(str) (Method)

This function decodes a URL encoded string.


var s = unescapeProperly("hello%20world%21%21"); //s = "hello world!!"

7. STSHtmlEncode(htmlString) (Method)

This function encodes an html string


var s = STSHtmlEncode("<p>sample text</p>");
//s = "&lt;p&gt;sample text&lt;/p&gt;"

8. TrimSpaces(str) (Method)

This method trims out the leading and trailing white spaces of a string. It doesn’t remove spaces created by special characters such as ‘\n’, \t’


var s = TrimSpaces("   Hello   World!!    "); //s = "Hello   World!!"

I intentionally put more spaces between ‘Hello’ and ‘World!!’ just to show that this method doesn’t remove any spaces between words.

9. TrimWhiteSpaces(str) (Method)

This method trims out the leading and trailing white spaces of a string. It also removes spaces created by special characters such as ‘\n’, \t’


var s = TrimWhiteSpaces("\n\nHello   World!!\t\t"); //s = "Hello   World!!"

10. LoginAsAnother(url, bUseSource)

This method is used to login as different user.(as the name says)

url(string): the url of the page to which the new user has to be sent after login.

bUseSource(boolean): A boolean that indicates that the source will be added to the url, otherwise the source will be the window.location.href. This parameter is optional, default is false.


<a href="#" onclick="javascript:LoginAsAnother('\u002f_layouts\u002fAccessDenied.aspx?loginasanotheruser=true', 0)">Log on as a different user</a>

11. STSPageUrlValidation(url)

This function validates a url if it starts with “http” or “/” or “:” ONLY. It returns the url value back if it is a valid url and an empty value if it is an invalid url. If the url is not valid, an alert message is displayed that says “Invalid page URL:”.


var s = STSPageUrlValidation("praneethmoka.wordpress.com"); //s = praneethmoka.wordpress.com

var s = STSPageUrlValidation(":praneethmoka.wordpress.com"); //s = "";

var s = STSPageUrlValidation("w.wordpress.com"); //s = "w.wordpress.com";

Now please don’t ask me what kind of a validation this is.

STSPageUrlValidation(url) in turn calls a method PageUrlValidation(url) and here’s the code for PageUrlValidation method


function PageUrlValidation(url)
{ULSA13:;
  if((url.substr(0, 4) == "http") || (url.substr(0, 1) == "/") || (url.indexOf(":") == -1))
  {
      return url;
  }
  else
  {
      var L_InvalidPageUrl_Text="Invalid page URL: ";
      alert(L_InvalidPageUrl_Text);
      return "";
  }
}

I will update this post as I find more useful javascript stuff.

References:
http://community.zevenseas.com/Blogs/Tanmay/Lists/Posts/Post.aspx?ID=8
http://ruudheemskerk.net/archive/2010/08/03/helpful-sharepoint-javascript-functions.aspx

Advertisements
 
10 Comments

Posted by on January 12, 2012 in SharePoint

 

Tags: , ,

10 responses to “Some useful Javascript variables/functions in Sharepoint

  1. Singapore Web Design, Singapore SEO, Singapore Internet Marketing

    April 27, 2012 at 6:45 am

    Thank you a lot for sharing this with all folks you actually know what you are speaking about! Bookmarked.

     
  2. Singapore Web Design, Singapore SEO, Singapore Internet Marketing

    April 27, 2012 at 11:19 am

    I am now not sure where you’re getting your info, however great topic. I needs to spend a while learning much more or figuring out more. Thanks for excellent info I was in search of this information for my mission.

     
  3. Kensley Lewis

    May 6, 2013 at 2:05 pm

    Is there a way to detect if a SharePoint session variable exists via JavaScript?

     
  4. Devang

    February 3, 2014 at 8:09 am

    Thanks a lot for sharing this wonderful collection.

     
  5. プロキオン

    September 7, 2016 at 2:52 am

    中高年男性は、性機能の低下に悩まされるなどの異常が増加します。そのため精力増強剤のユーザー数が日本中にいます。その中でも多種多様な強壮剤中、一押しは、プロキオンです。実際の食品の栄養をふんだんに配合された強壮剤で性機能低下を改善するアイテムとしてヒット中です。

     

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

 
%d bloggers like this: