1

I use "_spPageContextInfo.webAbsoluteUrl" to detect the site url.

How to identity your current site which you are surfing is root site or subsite by javascript? If subsite, which level of subsite is it? The solution is only javascript and only bases on the site url.

Thanks for helping.

iamsankalp89
  • 4,607
  • 2
  • 15
  • 36
anhtv13
  • 1,636
  • 4
  • 30
  • 51

1 Answers1

2

You can use _spPageContextInfo.siteServerRelativeUrl.

If _spPageContextInfo.siteServerRelativeUrl equals to / then you are definitely in the root site.

In the subsite, the value of _spPageContextInfo.siteServerRelativeUrl would be /subsite1.

In the sub-subsite, the value of _spPageContextInfo.siteServerRelativeUrl would be /subsite1/subsite1_1.

Another option would be, to check if _spPageContextInfo.webAbsoluteUrl equals to _spPageContextInfo.siteAbsoluteUrl. This will be true only in case of the root site. So, if(_spPageContextInfo.webAbsoluteUrl == _spPageContextInfo.siteAbsoluteUrl), then you would be in the root site.

To detect the level of subsite, you can try it as below:

var value = _spPageContextInfo.webServerRelativeUrl;

var level = value.split('/').length -1;
Gautam Sheth
  • 2,442
  • 1
  • 17
  • 16
  • Good idea for detecting root site and sub site. But I want to go deeper: if current site is sub site, which level of sub site is it? – anhtv13 Sep 07 '17 at 09:31
  • if my root site is "mywebsite:8888/sites/mynewsite", variable "_spPageContextInfo.webServerRelativeUrl" is "/sites/mynewsite" and your code is incorrect. – anhtv13 Sep 07 '17 at 09:46