2013-03-07 36 views
1

我正在开发一个严重依赖javascript的浏览器历史记录操作的站点,并且只使用一个实际的页面文件。我希望脚本在用户点击网站的基本网址时运行一个函数,但我不确定哪种方法是合适的。想象一下,我可以快速比较当前的窗口位置,但如果用户输入的是www而不是http://,或者没有输入,那该怎么办?有些东西告诉我这应该很容易。仅在基本URL上运行的JS函数

if (window.location.href == 'http://mysite.com') { 
    console.log('you hit the base url, yay'); 
    myFunction(); 
} 

回答

1

如果基本URL,你的意思是有没有路径组件或哈希代码,你可以检查这个如下:

if (window.location.pathname==='/' && window.location.hash==="") { 
    console.log('you hit the base url, yay'); 
    myFunction(); 
} 
+0

@ironchefpyhon这正是我正在寻找的,但我似乎无法得到它的工作。有任何想法吗? – 2013-03-07 21:05:52

+0

当然,只需在“base url”和其他网址处输入“console.log(window.location.pathname)”,你就知道要测试什么。我去了google.com,然后在Chrome开发者控制台中输入了console.log(window.location.pathname ==='/')',我得到了'true'。 – ironchefpython 2013-03-07 21:07:51

+0

我想我尝试添加您的示例的早期版本,包括您的当前编辑,我设法让它工作。谢谢! – 2013-03-07 21:17:39

4

这听起来像你想隔离URL的路径部分。

function isHomePage() { 
    return window.location.pathname === '/' || window.location.pathname === ''; 
} 

这应该包括你的基地,即使URL是一样的东西

https://www2.example.com:443/#hash 
+0

不是一个坏主意。 – 2013-03-07 20:57:48

+0

不错的功能,但由于我没有重复使用它,我只是简单地添加一个条件语句。谢谢您的帮助! – 2013-03-07 21:21:14

+0

@Staffan我建议将它封装在一个函数中,以便下一个阅读代码的人不必停下来尝试弄清楚你的意图是什么。 – 2013-03-07 21:42:12

1

JavaScript可以部分访问当前URL。对于这个网址:

http://mysite.com/example/index.html

window.location.protocol = "http" 
window.location.host = "mysite.com" 
window.location.pathname = "example/index.html" 

让它务必使用主机属性

if (window.location.host === 'mysite.com') { 
    console.log('you hit the base url, yay'); 
    myFunction(); 
}