前端無後端代理情況下,可直接呼叫各大廠商提供的 JSONP 介面取得訪客 IP 與地理位置。本文整理 8 家常用 API 的請求網址、回傳格式、前端調用範例,並附上跨域與可用性測試建議。
| 提供商 | 介面網址 | 回傳格式 | 備註 |
|---|---|---|---|
| 騰訊 | https://fw.qq.com/ipaddress | JS 變數 IPData 陣列 | [IP, '', 省份, 城市] |
| 新浪 | https://int.dpool.sina.com.cn/iplookup/iplookup.php?format=js | JS 物件 remote_ip_info | 含國家、省、市、ISP、經緯度 |
| 搜狐 | https://pv.sohu.com/cityjson | JS 物件 returnCitySN | 含 cip、cid、cname |
https://j.maxmind.com/app/geoip.js | JS 變數 | 需翻牆,國內不可用 | |
| 有道 | https://www.youdao.com/smartresult-xml/search.s | XML/JS | 參數較複雜 |
| 1616 | https://w.1616.net/chaxun/iptolocal.php | JS | 穩定性一般 |
| 126 | https://ip.ws.126.net/ipquery | JS | 網易出品 |
| hao123 | https://app.hao123.com/ipquery/getcity.php?rtype=2 | JSONP | 支援 callback 參數 |
<script src="https://fw.qq.com/ipaddress"></script>
<script>
document.write('你的 IP:' + IPData[0] + ',來自:' + IPData[2] + IPData[3]);
</script>
<script src="https://int.dpool.sina.com.cn/iplookup/iplookup.php?format=js"></script>
<script>
if (typeof remote_ip_info !== 'undefined' && remote_ip_info.ret === 1) {
console.log('IP:', remote_ip_info.start);
console.log('國家:', unescape(remote_ip_info.country));
console.log('省份:', unescape(remote_ip_info.province));
console.log('城市:', unescape(remote_ip_info.city));
console.log('ISP:', unescape(remote_ip_info.isp));
}
</script>
<script src="https://pv.sohu.com/cityjson"></script>
<script>
console.log('IP:', returnCitySN.cip);
console.log('地區代碼:', returnCitySN.cid);
console.log('地區名稱:', returnCitySN.cname);
</script>
https://api.ip.sb/geoip、https://ipapi.co/json/)。localStorage 快取 24 小時,減少外部請求。// 純 JSON、支援 HTTPS、無 callback 參數、CORS 開放
fetch('https://ipapi.co/json/')
.then(r => r.json())
.then(data => console.log(data.ip, data.city, data.country_name));
上述服務免費額度每日 1,000 次,商業專案建議自建 MaxMind GeoLite2 資料庫或採用付費 API(ipinfo.io、ipgeolocation.io 等)。