You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在纯HTML网站中通过JavaScript显示当前访问的页面路由

实现方案

你要的效果用原生JavaScript就能实现,不需要依赖后端框架,直接调用浏览器自带的window.locationAPI获取当前路由即可,以下是完整可运行的代码:

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>路由展示示例</title>
</head>
<body>
    <!-- 路由提示展示位置 -->
    <div id="route-text"></div>

    <script>
        // 读取当前访问路径,例如访问 http://www.example.com/example 时得到 '/example'
        const path = window.location.pathname
        // 移除路径开头的斜杠,得到路由名称 'example'
        const route = path.replace(/^\/+/, '')
        // 拼接展示文本写入页面
        document.getElementById('route-text').textContent = `you visited the ${route} page`
    </script>
</body>
</html>

不同场景适配说明

  • 多页面静态站点:把上述代码复制到每个页面中,或者将JS逻辑抽为独立的.js文件,在所有页面引入即可
  • 哈希路由单页应用:如果你的站点用哈希路由(路径格式为http://www.example.com/#/example),将读取路径的代码替换为const path = window.location.hash.slice(2)即可
  • 多层路径场景:如果路由有多层级比如/user/setting,想只取最后一级作为路由名,可以改用const route = path.split('/').filter(Boolean).pop()处理

内容的提问来源于stack exchange,提问作者sk.anu

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.03 16:24:04