因某次項目緣由,要作一個簡單的數據埋點,後端說可能會拿不到個人IP,但願前端能獲取到,因而乎我就各類百度谷歌查資料,終於在羣友的幫助下找到了一篇獲取IP的文章,由於是英文的,過了好久我都不記得了連接了,怕之後忘記,就記錄下來前端
// 獲取用戶ip
export function getUserIP(onNewIP) { // onNewIp - your listener function for new IPs
//compatibility for firefox and chrome
var myPeerConnection = window.RTCPeerConnection || window.mozRTCPeerConnection || window.webkitRTCPeerConnection;
var pc = new myPeerConnection({
iceServers: []
}),
noop = function() {},
localIPs = {},
ipRegex = /([0-9]{1,3}(\.[0-9]{1,3}){3}|[a-f0-9]{1,4}(:[a-f0-9]{1,4}){7})/g
function iterateIP(ip) {
if (!localIPs[ip]) onNewIP(ip)
localIPs[ip] = true
}
//create a bogus data channel
pc.createDataChannel("")
// create offer and set local description
try{
pc.createOffer(function(sdp) {
sdp.sdp.split('\n').forEach(function(line) {
if (line.indexOf('candidate') < 0) return
line.match(ipRegex).forEach(iterateIP)
})
pc.setLocalDescription(sdp, noop, noop)
},function(sdp){
console.log('fail')
})
} catch (err) {
console.log(err)
}
//listen for candidate events
pc.onicecandidate = function(ice) {
if (!ice || !ice.candidate || !ice.candidate.candidate || !ice.candidate.candidate.match(ipRegex)) return
ice.candidate.candidate.match(ipRegex).forEach(iterateIP)
};
}
複製代碼
原理彷佛是模擬請求獲取請求端IP。本身也是個菜鳥,只知其一;不知其二。web
import {getUserIP} from '@/utils/getip'
let userIP = ''
if (!userIP) {
getUserIP(function(ip) {
userIp = ip
})
}
複製代碼
這樣就獲取到了IP。chrome