1

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

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

4 回答 4

4

听起来您想隔离 URL 的路径部分。

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

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

https://www2.example.com:443/#hash
于 2013-03-07T20:55:51.477 回答
2

window.location.href始终包含协议,因此如果用户在输入 URL 时省略了协议,则没有问题。

于 2013-03-07T20:52:17.820 回答
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();
}
于 2013-03-07T20:57:06.920 回答
1

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

if (window.location.pathname==='/' && window.location.hash==="") {
    console.log('you hit the base url, yay');
    myFunction();
}
于 2013-03-07T20:56:44.647 回答