Kamyar
Kamyar

Reputation: 18797

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

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

... [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.

Upvotes: 33

Views: 25788

Answers (6)

Ewald Bos
Ewald Bos

Reputation: 1770

What about the following:

if (location.pathname == "/" || (window.location.href.indexOf("Index") > -1)){

  console.log("do stuff") 

}

be aware that the 'Index' is case sensitive

Upvotes: 0

Ronnie Smith
Ronnie Smith

Reputation: 18595

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 }

Upvotes: 1

Rob W
Rob W

Reputation: 349122

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

Upvotes: 82

Stephan
Stephan

Reputation: 43053

Try this more robust regular expression:

Regex

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


Description

Regular expression visualization


Demo

Debuggex Demo

Upvotes: 1

Ortiga
Ortiga

Reputation: 8824

I think

if(window.location == window.location.hostname) {
    //is root
}

Edit: Do not use this, see comment

Upvotes: 0

Mic
Mic

Reputation: 25164

With a regular expression like:

(/^https?\:\/\/[^\/]+\/?$/).test(window.location.href)

Upvotes: 0

Related Questions