Sometimes from client side, you need to know the current web url. And for this little information you don’t want to call EcmaScript’s load function to get information from server side. Actually the information can be found without any server call. You can access the information from ClientContext as shown below.
var context = new SP.ClientContext();
var relativeWebUrl = context.get_url();
Remember the get_url method will only return relative url of the site. As shown in the following table:
Site Collection Url | Site Url | context.get_url() response |
---|---|---|
http://mysite.com | http://mysite.com | / |
http://mysite.com | http://mysite.com/site1 | /site1 |
http://mysite.com/sites | http://mysite.com/sites/site1 | /sites/site |
So if you need to know the full url of the site you can do so easily with the following script:
function getFullWebUrl() {
var context = new SP.ClientContext();
var relativeWebUrl = context.get_url();
var fullWebUrl = window.location.protocol + '//' + window.location.host + relativeWebUrl ;
alert(fullWebUrl);
}