简体   繁体   中英

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?

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.

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.

You could use

if (document.location.pathname === '/' || 
    document.location.pathname.indexOf('index') >-1 ) {
   return true;
 }

If you have access to the actual page and not just the script then you should follow @Ben Everard's advice.

Just make sure you include the snippet he proposes before your script..

There isn't a direct link between files and URLs. Additionally, index.html does not need to be in the site's root and the default page does not need to be index.html .

If you want a generic solution, you're probably out of luck. If you want a solution for your particular case, you can just provide that info from the page itself, eg defining an ID or class name:

<body class="index">

... or a JavaScript variable:

// Pick one
var page = 'index';
var isIndex = true;

If all you want is some simple string manipulation with current location, grab the pathname property of the window.location object:

// Untested
if( window.location.pathname=="/" || window.location.pathname=="/index.html" ){
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM