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.
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).
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.
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:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With