How to check if the user is visiting the site's root url?

21,416

Solution 1

The easiest JavaScript method is:

var is_root = location.pathname == "/"; //Equals true if we're at the root

Even http://example.com/?foo=bar#hash will produce the right result, since the pathname excludes the query string and location hash.

Have a look:

http://anything-but-a-slash/                  Root
                           /?querystring      Root
                           /#hash             Root
                           /page              Not root

If you have index file(s) at your root folder, have a look at the following example:

var is_root =/^\/(?:|index\.aspx?)$/i.test(location.pathname);

The previous line is using a regular expression. Special characters have to be escaped, the /i postfix makes the pattern case-insensitive. If you want the case to match, omit the i flag.

The same regular expression presented graphically:

Regular expression visualization

Solution 2

Try this more robust regular expression:

Regex

var isRoot =/^(\/|\/index\.asp|\/index\.aspx)$/i.test(location.pathname);


Description

Regular expression visualization


Demo

Debuggex Demo

Solution 3

Testing for pathname of "/" failed when I ran my app in debug/preview mode from my online IDE. In other words it normally is served with a clean url (no .html) except when I serve it from Cloud9 in which case it is served with index.html.

So, this is working for me:

if(window.location.pathname.length == 1 || window.location.pathname.length == 0 || window.location.pathname === "/index.html" || window.location.pathname === "/index"){ //I'm at the app root }

Share:
21,416
Kamyar
Author by

Kamyar

Currently a Senior Engineer at Claimsforce

Updated on July 22, 2022

Comments

  • Kamyar
    Kamyar almost 2 years

    I'd like to fire up some script if the user is visiting my site's root url.

    For example, I want to do something in my view when the user is visiting

    • www.example.com
    • example.com
    • www.example.com/
    • http://www.example.com
    • http://example.com

    ... [Various combinations of the above.]

    And not for www.example.com/anything else.
    What is the safest way to check this in a view page of a ASP.NET MVC 3 [Razor] web site and javascript? Also, is there any way to find out using only javascript?
    Thank you.