Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I tell if a user is on index.html?

I use document.URL to detect if a user is on index.html:

if(document.URL.indexOf("index") >-1) return true;

But if the user types "mydomain.com" or "mydomain.com/" then the test returns false.

I could try:

if(document.URL ==="http://myDomain.com") return true;

But I want to use this code on different domains. Any suggestions?

like image 515
Chris Tolworthy Avatar asked Nov 29 '22 03:11

Chris Tolworthy


2 Answers

javascript Location object has many useful properties, in particular, you can examine location.pathname.

Basically, you're on the "index" page if the pathname is 1) empty 2) is equal to a slash / 3) starts with index or /index.

 var p = window.location.pathname;

 if (p.length === 0 || p === "/" || p.match(/^\/?index/))
     alert ("on the index page!")

See Javascript .pathname IE quirk? for the discussion of leading slash issues.

like image 33
georg Avatar answered Dec 05 '22 00:12

georg


There are so many permutations of URL that could mean that a user is on index.html. Instead could you not put a var within that file:

<script type="text/javascript">
    on_index = true;
</script>

Just check if on_index is not undefined and is true. That'll be accurate 100% of the time.

like image 84
Ben Everard Avatar answered Dec 04 '22 22:12

Ben Everard