纯前端获取当前用户IP和归属地

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>IP Address</title>
</head>
<body>
<p id="content1"></p>
<p id="content2"></p>
<script>
    function getIpAddress() {
        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();
            document.getElementById('content1').innerText = text;
            let ipAddress = {ip: "", location: "", type: ""}
            try {
                let ip = text.substring(text.indexOf("[")+1,text.indexOf("]")).trim();
                ipAddress.ip = ip;
                let other = text.substring(text.indexOf("来自:")+3).trim();
                let arr = other.split(" ");
                ipAddress.location = arr[0];
                ipAddress.type = arr[1];
            }catch (e) {
                console.error(e)
            }
            document.getElementById('content2').innerText = JSON.stringify(ipAddress);
        })
    }

    getIpAddress();
</script>
</body>
</html>
posted @ 2023-07-25 10:16  小小爬虫  阅读(1379)  评论(0编辑  收藏  举报