检查主页是否使用window.location



是否可以使用window.location检查我是否在网站的主页/索引上?

我目前正在使用检查url

window.location.href.indexOf("/category/something")

但是我怎样才能查看主页呢?它不包含任何分段。

注意:我不知道主页的URL是什么,所以我不能使用像window.location.href.indexOf("myhomepage.html") 这样的URL名称

更新:我唯一的线索是主页没有URL段。

术语homepage本身是一个相当模糊的结构,在技术上是不可识别的。根据您的屏幕大小、设备、凭据、浏览器、日期/时间、地理位置等,您可能有几个不同的登录页。

确保您处于其中一个登录页的唯一方法是在向域(例如http://www.example.com)发出初始GET请求期间进行控制。

因此,如果你已经在页面上了,就没有真正的方法知道你是如何到达那里的,如果这是该域提供的默认页面,尽管有一些技巧,但你可以尝试获得一个通用的(尽管很容易出错)想法。

例如,您可以编译一个常见主页路径列表:

var homepages = [ '/', 'index.html', 'index.htm', 'index.php', 'main.html', 'main.htm', 'homepage.html', 'index2.htm' ]; 

然后与提供的window.location.pathname:进行比较

if (homepages.indexOf(window.location.pathname) >= 0) {
    // we might be on a "homepage"
}

许多网站的主页,包括stackoverflow,都包含指向同一主页的链接。

// browser url = http://example.com
<a href="http://example.com">my site</a>

如果你有访问源,你可以识别这个链接的服务器端

<a id="homepage" href="http://example.com"/>my site</a>

因此,要检查您是否在主页上:

document.addEventListener('DOMContentLoaded', function(e) {
  var link = document.querySelector('#homepage');
  if (link.href == window.location.href) {
    //i'm on the homepage
  }
})

所以我刚刚看到你对这个问题的更新。如果你知道没有url段,window.location.pathname不是总是"/"

如果你只是简单地执行window.location并检查其中的args,如果没有附加页面/路径,url与原点匹配等,这是否不足以检测——Idk,我从来没有这样做过?这可能也适用于.NET和"其他"类型的HTML命名约定(即index.HTML与index.htm)。此外,如果有人更改了文档根目录或主页指针,你或多或少会知道(也就是不在乎),因为window.location你可以检查以下内容:

window.location
Location {replace: function, assign: function, ancestorOrigins: DOMStringList, origin: "http://stackoverflow.com", hash: ""…}ancestorOrigins: DOMStringListassign: function () { [native code] }hash: ""host: "stackoverflow.com"hostname: "stackoverflow.com"href: "http://stackoverflow.com/"origin: "http://stackoverflow.com"pathname: "/"port: ""protocol: "http:"reload: function reload() { [native code] }replace: function () { [native code] }search: ""toString: function toString() { [native code] }valueOf: function valueOf() { [native code] }__proto__: Location

其具有CCD_ 9。这很好地表明了主页的"害羞"。

JavaScript只知道它的当前上下文。它不知道它在网站的层次结构中的位置,所以不,你不能在不知道主页的URL 的情况下检查你是否在主页上

最新更新