Dan Dinu
Dan Dinu

Reputation: 33

check if user is visiting pure root url

I'd like to run a js script if a user is visiting my site's root url. I am using this code:

<script type="text/javascript">
    if(location.pathname == "/") {
        window.open ('#107','_self',false);
    }
</script>

However http://example.com/?foo=bar#hash will also run the script, since the pathname excludes the query string and location hash.

It currently behaves like this:

http://example/                  Root
              /?querystring      Root
              /#hash             Root
              /page              Not root

I want it to behave like this:

http://example/                  Root
              /?querystring      Not root
              /#hash             Not root
              /page              Not root

Any suggestions? Thanks.

Upvotes: 3

Views: 4472

Answers (3)

jfriend00
jfriend00

Reputation: 707716

You can just test for all three components:

<script type="text/javascript">
    if(location.pathname == "/" && 
        location.hash.length <= 1 && 
        location.search.length <= 1) {
        window.open ('#107','_self',false);
    }
</script>

Upvotes: 2

Matt Zeunert
Matt Zeunert

Reputation: 16571

You can concatenate the pathname, location.search and location.hash.

var fullPath = location.pathname + location.search + location.hash;
if(fullPath == "/") { /* whatever */ }

Upvotes: 3

Umur Kontacı
Umur Kontacı

Reputation: 35478

Use window.location.href instead

Upvotes: 4

Related Questions