Reputation: 18797
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.
Upvotes: 33
Views: 25788
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
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
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:
Upvotes: 82
Reputation: 43053
Try this more robust regular expression:
Regex
var isRoot =/^(\/|\/index\.asp|\/index\.aspx)$/i.test(location.pathname);
Description
Demo
Upvotes: 1
Reputation: 8824
I think
if(window.location == window.location.hostname) {
//is root
}
Edit: Do not use this, see comment
Upvotes: 0
Reputation: 25164
With a regular expression like:
(/^https?\:\/\/[^\/]+\/?$/).test(window.location.href)
Upvotes: 0