Javascript 如何检查用户当前所在的html文件?

Javascript 如何检查用户当前所在的html文件?,javascript,html,Javascript,Html,我正在尝试检查用户是否在index.html中,我已经记下了这段代码 console.log(window.location.pathname) if ( window.location.pathname === '/' ){ //code for index page console.log("In index") }else{ console.log("Not in index") } 现在它总是返回为false,即使我完全在in

我正在尝试检查用户是否在index.html中,我已经记下了这段代码

console.log(window.location.pathname)

if ( window.location.pathname === '/' ){
   //code for index page
   console.log("In index")
}else{
   console.log("Not in index")
}
现在它总是返回为
false
,即使我完全在index.html文件中

这是我从chrome上得到的日志

/C:/Users/krist/Documents/tuts/firebase-functions/public/index.html

当我输入整个路径时,它可以工作,但我只是担心它太长,如果路径发生变化,就会把代码弄乱。我该怎么做呢?

与其尝试从浏览器中获取URL,不如放一些

<script>
const isIndexPage = true;
</script>

根据站点的布局方式,您可能需要检查更多内容,例如,是否存在多个子目录,并且您希望知道自己不在其中一个子目录中。这就是为什么我不推荐它的部分原因。

如果我是你,我会将代码放在服务器上而不是本地文件上,这样会更容易预测-路径更改不再是问题。你是说像firebase服务器一样吗?对不起,我是一个全新的web开发人员。任何服务器的托管内容都可以通过web浏览器访问
   window.location.pathname.endsWith('index.html')
|| window.location.pathname.endsWith('/')