HTML如何获取当前域名、前缀、IP及URL参数?一文详解实操方法

前沿博客
5天前发布 /正在检测是否收录...

HTML获取域名、前缀、IP及参数的实现方法

头图
在前端开发中,有时候需要获取当前页面的域名、IP等信息,或者解析URL中的参数。这些需求在调试、数据统计或个性化展示时很常见。下面就来聊聊如何用纯HTML(结合JavaScript)实现这些功能,代码简单易懂,新手也能轻松上手~

一、获取当前域名和前缀

域名和前缀的获取主要通过JavaScript的 window.location 对象,它包含了当前URL的所有信息。

// 获取完整域名(包含www等前缀)
const domain = window.location.hostname;
console.log('完整域名:', domain); // 例如:www.example.com

// 获取域名前缀(去除www.)
const prefix = domain.startsWith('www.') ? domain.replace('www.', '') : domain;
console.log('域名前缀:', prefix); // 例如:example.com

// 获取不带端口的域名(如果有端口号,如8080,会被去除)
const domainWithoutPort = domain.split(':')[0];
console.log('无端口域名:', domainWithoutPort);

核心原理: window.location.hostname 会返回域名部分,通过字符串处理(比如 startsWith 和 replace )可以去掉前缀或端口号。

二、获取当前IP地址(需借助第三方服务)

由于浏览器安全限制,无法直接通过HTML获取用户IP,但可以借助第三方API:

// 通过公共API获取IP(示例:ipify.org)
fetch('https://api.ipify.org?format=json')
  .then(response => response.json())
  .then(data => {
    const userIP = data.ip;
    console.log('用户IP:', userIP);
  })
  .catch(error => {
    console.log('获取IP失败:', error);
  });

注意:这类API可能存在跨域问题,部分场景需要后端转发请求。如果是本地调试,也可以用 localhost 或 127.0.0.1 模拟IP。

三、获取URL传递的参数

URL参数(如 ?id=123&name=test )的解析是前端常用功能,可通过以下方法实现:

// 方法1:手动解析(适合简单场景)
const urlParams = new URLSearchParams(window.location.search);
const id = urlParams.get('id');
const name = urlParams.get('name');
console.log('参数id:', id);
console.log('参数name:', name);

// 方法2:封装成函数(支持复杂参数)
function getUrlParams() {
  const params = {};
  const search = window.location.search.slice(1);
  const pairs = search.split('&');
  
  pairs.forEach(pair => {
    if (!pair) return;
    const [key, value] = pair.split('=');
    params[key] = decodeURIComponent(value || '');
  });
  
  return params;
}

const allParams = getUrlParams();
console.log('所有参数:', allParams);

场景示例:当URL是 https://example.com/page?product=phone&price=999 时, getUrlParams() 会返回 { product: 'phone', price: '999' } 。

四、在HTML页面中显示信息

把上述功能整合到HTML页面,实时展示结果:

<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <title>URL信息获取</title>
</head>
<body>
  <h3>当前页面信息</h3>
  <div>完整域名:<span id="domain"></span></div>
  <div>域名前缀:<span id="prefix"></span></div>
  <div>用户IP:<span id="ip"></span></div>
  <div>URL参数:<span id="params"></span></div>

  <script>
    // 获取域名和前缀
    const domain = window.location.hostname;
    const prefix = domain.startsWith('www.') ? domain.replace('www.', '') : domain;
    document.getElementById('domain').textContent = domain;
    document.getElementById('prefix').textContent = prefix;

    // 获取IP(第三方API)
    fetch('https://api.ipify.org?format=json')
      .then(res => res.json())
      .then(data => {
        document.getElementById('ip').textContent = data.ip || '获取失败';
      })
      .catch(() => {
        document.getElementById('ip').textContent = '无法获取IP(请检查网络)';
      });

    // 获取并显示参数
    const urlParams = new URLSearchParams(window.location.search);
    let paramsText = '无参数';
    if (urlParams.toString()) {
      paramsText = '';
      for (const [key, value] of urlParams.entries()) {
        paramsText += `${key}=${value}, `;
      }
      paramsText = paramsText.slice(0, -2); // 去掉最后多余的逗号
    }
    document.getElementById('params').textContent = paramsText;
  </script>
</body>
</html>

效果如下:打开页面后,会自动显示域名、前缀、IP和参数,无需手动操作。

URL信息获取

当前页面信息

完整域名:
域名前缀:
用户IP:
URL参数:

五、注意事项

  • 跨域限制:获取IP需借助第三方API,可能受跨域策略影响,本地调试时可使用 jsonp 或后端代理。
  • 安全考量:IP和域名信息属于用户环境数据,敏感场景下需注意隐私保护,避免直接存储或传输。
  • 兼容性: URLSearchParams 在旧版浏览器(如IE)中可能需要polyfill,建议搭配babel插件使用。

通过以上方法,就能在HTML页面中轻松获取域名、IP和URL参数啦~ 有问题可以随时问,一起折腾前端小技巧!

喜欢就支持一下吧
点赞 0 分享 赞赏
评论 抢沙发
OωO
取消 登录评论
SSL