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

如何编写JavaScript脚本识别特定URL并在控制台打印信息?

检测当前URL并输出控制台提示的JavaScript实现

针对你的需求,这里提供两种场景的实现方案,覆盖普通多页网站和单页应用的情况:

一、普通多页网站(页面刷新式导航)

这种场景下每次导航都会刷新页面,我们只需要在页面加载完成后检查当前URL即可:

// 替换成你要检测的目标URL
const targetUrl = "https://example.com";

// 页面加载完成后执行检查
window.addEventListener('load', () => {
  checkCurrentUrl();
});

function checkCurrentUrl() {
  const currentUrl = window.location.href;
  if (currentUrl === targetUrl) {
    console.log(`You are on url:[${targetUrl}].`);
  }
}

说明

  • window.location.href 获取当前页面的完整URL(包含协议、域名、路径等)
  • load 事件确保页面资源全部加载完成后再执行检查
  • 如果只需要匹配URL的路径部分(比如忽略域名),可以用 window.location.pathname 代替 href,示例:
    const targetPath = "/blog";
    if (window.location.pathname === targetPath) {
      console.log(`You are on url:[${window.location.href}].`);
    }
    

二、单页应用(无刷新式导航)

单页应用(如React、Vue项目)的路由切换不会刷新页面,除了页面加载时的检查,还需要监听路由变化:

const targetUrl = "https://example.com/dashboard";

// 页面加载时先检查一次
checkCurrentUrl();

// 监听浏览器前进/后退导致的URL变化
window.addEventListener('popstate', () => {
  checkCurrentUrl();
});

// 如果你用框架自带的路由,建议用框架原生监听方法(更可靠)
// 比如React Router v6+:
// import { useLocation } from 'react-router-dom';
// export default function App() {
//   const location = useLocation();
//   useEffect(() => {
//     if (location.href === targetUrl) {
//       console.log(`You are on url:[${targetUrl}].`);
//     }
//   }, [location]);
// }

function checkCurrentUrl() {
  const currentUrl = window.location.href;
  if (currentUrl === targetUrl) {
    console.log(`You are on url:[${targetUrl}].`);
  }
}

扩展:匹配多个目标URL

如果需要检测多个URL,可将目标存入数组,用includes方法检查:

const targetUrls = ["https://example.com", "https://example.com/about", "https://example.com/contact"];

function checkCurrentUrl() {
  const currentUrl = window.location.href;
  if (targetUrls.includes(currentUrl)) {
    console.log(`You are on url:[${currentUrl}].`);
  }
}

脚本使用方式

  • 将代码放入外部JS文件,然后在HTML中通过<script src="your-script.js"></script>引入(建议放在</body>标签前)
  • 也可以直接把代码写在HTML的<script>标签里

内容的提问来源于stack exchange,提问作者BDEVELOPER

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 03:12:57