vue2获取当前设备的 IP 地址以及位置信息

 

 
  data() {
    return {
      ipAddress: { ip: "", location: "", type: "" },
    }
  },
  mounted() {
    this.getIpAddress();
    console.log(this.ipAddress);//{ip: 'xxx.xx.xxx.xxx', location: '中国上海xx', type: 'xx'}
  },
  methods: {
    getIpAddress() { //获取ip, 位置
      let year = new Date().getFullYear();
      fetch(`https://${year}.ip138.com/`).then(x => x.text()).then(h => {
        let domParser = new DOMParser();
        let doc = domParser.parseFromString(h, "text/html");
        let text = doc?.querySelector('p')?.innerText?.trim();
        console.log(text)//您的iP地址是:[xxx.xx.xxx.xxx ] 来自:中国上海xx xx
        try {
          let ip = text.substring(text.indexOf("[") + 1, text.indexOf("]")).trim();
          this.ipAddress.ip = ip;
          let other = text.substring(text.indexOf("来自:") + 3).trim();
          let arr = other.split(" ");
          this.ipAddress.location = arr[0];
          this.ipAddress.type = arr[1];
        } catch (e) {
          console.error(e)
        }
      })
    },
   }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值