仅在基本URL上运行的JS函数

时间:2013-03-07 20:49:49

标签: javascript function url location

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

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

4 个答案:

答案 0 :(得分:4)

听起来您想要隔离网址的路径部分。

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

这应该涵盖你的基础,即使URL类似

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

答案 1 :(得分:2)

window.location.href always includes the protocol,因此如果用户在输入网址时省略了这一点,则没有问题。

答案 2 :(得分:1)

如果通过基本网址,您的意思是没有路径组件或哈希片段,您可以按如下方式检查:

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

答案 3 :(得分: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();
}