Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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.

like image 937
Kamyar Avatar asked Nov 11 '11 22:11

Kamyar


People also ask

How do I find the root URL?

You can determine your server's root URL by browsing to a page on your website and observing the address in the location/address entry field of the browser. The root URL is the section between the colon-slash-slash (://) and the next slash (/), omitting any port number (:portno).

How do you check if the user came from a specific link or website in Javascript?

To check if the user came from a specific website or by clicking a link to your website, you can use the referrer property in the global document object. // Check the link of website user came from const linkOfTheWebsiteUserCame = document.


1 Answers

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

like image 168
Rob W Avatar answered Jan 28 '23 08:01

Rob W