最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - check if user is visiting pure root url - Stack Overflow

programmeradmin1浏览0评论

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 /?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.

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./?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.

Share Improve this question asked Aug 27, 2012 at 10:59 Dan DinuDan Dinu 331 silver badge3 bronze badges 1
  • I needed your opposite case so Your code as it is without a fix was what I exactly after, thank you :) – Bishoy Hanna Commented Jan 10, 2015 at 5:08
Add a ment  | 

3 Answers 3

Reset to default 4

Use window.location.href instead

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

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

You can just test for all three ponents:

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

评论列表(0)

  1. 暂无评论