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

如何使用JavaScript检测页面URL并按域名执行不同操作

实现方案

核心检测方法

你可以直接使用浏览器原生的window.location对象检测当前页面的地址信息,其中window.location.hostname属性可以直接获取当前页面的域名(不含端口、路径等冗余内容),完全匹配你的需求。

完整实现代码

以下代码既可以直接内嵌到HTML的<script>标签中,也可以写入独立的JavaScript文件引入:

// 获取当前页面域名
const currentDomain = window.location.hostname;

// 匹配coolsite.com及其所有子域名(如www.coolsite.com也会命中规则)
if (currentDomain.endsWith('coolsite.com')) {
  // 直接替换整个页面的内容
  document.documentElement.innerHTML = `
    <style>
      * {
        margin: 0;
        padding: 0;
        box-sizing: border-box;
      }
      .tip-container {
        min-height: 100vh;
        display: flex;
        align-items: center;
        justify-content: center;
        font-family: system-ui, sans-serif;
        padding: 20px;
        text-align: center;
      }
      .tip-content h1 {
        margin-bottom: 16px;
        color: #111827;
      }
      .tip-content p {
        margin-bottom: 24px;
        color: #374151;
        font-size: 16px;
      }
      .tip-content a {
        color: #2563eb;
        font-size: 18px;
        font-weight: 500;
      }
    </style>
    <div class="tip-container">
      <div class="tip-content">
        <h1>站点已迁移</h1>
        <p>本站点已更换域名,请访问新地址获取服务</p>
        <a href="https://example.com">前往 example.com</a>
      </div>
    </div>
  `;
  // 可选:终止后续代码执行,避免原页面的脚本继续运行报错
  throw new Error('站点已迁移,终止原有页面逻辑执行');
}

// example.com域名下无需额外处理,页面正常加载即可

注意事项

  • 建议将脚本放在HTML的<head>标签中加载,避免原页面内容先渲染再替换出现的闪烁问题
  • 如果你只需要精确匹配根域名coolsite.com(排除子域名),可以将判断条件修改为if (currentDomain === 'coolsite.com')即可
  • 如果需要判断协议、端口、路径等其他地址信息,可以使用window.location对象的其他属性:protocol(协议)、port(端口)、pathname(路径)、search(查询参数)等

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.23 19:06:04