当前位置:首页 > 行业动态 > 正文

html获取域名

在HTML中获取当前页面域名可通过JavaScript实现:使用 window.location.hostname可获取主域名,配合 document.domain能获取完整域名

获取当前页面域名的方法

使用 window.location 对象

HTML 本身无法直接获取域名,但可以通过 JavaScript 的 window.location 对象实现。location 对象包含当前页面的 URL 信息,hostname 属性可直接获取域名。

示例代码:

html获取域名  第1张

<script>
  // 获取完整域名(如:www.example.com)
  const domain = window.location.hostname;
  console.log("当前域名:", domain);
</script>

分解 URL 获取域名

若需手动解析 URL,可通过 location.href 结合字符串操作或正则表达式提取域名。

示例代码:

<script>
  // 获取完整 URL
  const url = window.location.href; // https://www.example.com:8080/path?query=1
  // 方法1:使用正则表达式提取域名
  const regex = /^https?://([^/:]+)/;
  const domain = url.match(regex)[1]; // 结果:www.example.com
  // 方法2:使用 split 分割字符串
  const domain2 = url.split('//')[1].split('/')[0]; // 结果:www.example.com
  console.log("正则提取域名:", domain);
  console.log("分割字符串提取域名:", domain2);
</script>

注意事项

  1. 端口号问题location.hostname 不包含端口号,若需包含端口号可使用 location.host
    • 示例:http://localhost:3000hostnamelocalhosthostlocalhost:3000
  2. 子域名处理hostname 会返回完整子域名(如 sub.example.com),若需主域名需进一步处理。
  3. 跨域限制:在 iframe 中获取其他域的域名可能受同源策略限制。

方法对比表

方法 结果(示例) 适用场景
location.hostname www.example.com 直接获取标准域名(推荐)
location.host www.example.com:80 需包含端口号时使用
正则表达式 www.example.com 自定义解析逻辑时
字符串分割 www.example.com 简单场景且无需正则时

相关问题与解答

问题1:如何判断当前页面是否属于特定域名?

解答:
可通过比较 location.hostname 与目标域名实现,判断是否为 example.com 的子域名或主域名:

const isTargetDomain = location.hostname === "example.com" || 
                      location.hostname.endsWith(".example.com");
console.log("是否为目标域名:", isTargetDomain);

问题2:如何在跨域 iframe 中获取来源域名?

解答:
受同源策略限制,直接获取跨域 iframe 的 location 会报错,需通过 postMessage 通信由 iframe 主动发送域名信息:

<!-主页面 -->
<iframe id="crossOriginFrame" src="https://other-domain.com"></iframe>
<script>
  const iframe = document.getElementById('crossOriginFrame');
  iframe.onload = () => {
    iframe.contentWindow.postMessage("请发送你的域名", "https://other-domain.com");
  };
  window.addEventListener("message", (event) => {
    if (event.origin === "https://other-domain.com") {
      console.log("收到的域名:", event.data);
    }
  });
</script>
<!-other-domain.com 页面 -->
<script>
  window.addEventListener("message", (event) => {
    if (event.data === "请发送你的域名") {
      event.source.postMessage(window.location.hostname, event.origin);
    }
  });
</script>
0