前端Vue中获取本机ip地址
前端Vue中获取本机ip地址methods方法getUserIP (onNewIP) { // 获取ip地址let MyPeerConnection = window.RTCPeerConnection || window.mozRTCPeerConnection || window.webkitRTCPeerConnectionlet pc = new MyPeerConnection({ice
·
前端Vue中获取本机ip地址
1.打开谷歌浏览器,地址栏输入chrome://flags,进入。
2.搜索Anonymize local IPs exposed by WebRTC,将其设置为Disabled。
methods方法
getUserIP (onNewIP) { // 获取ip地址
let MyPeerConnection = window.RTCPeerConnection || window.mozRTCPeerConnection || window.webkitRTCPeerConnection
let pc = new MyPeerConnection({iceServers: []})
let noop = function () {}
let localIPs = {}
let 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
}
pc.createDataChannel('')
pc.createOffer().then(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)
}).catch(function (reason) {
// An error occurred, so handle the failure to connect
})
// seen 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)
}
},
在created中调用ip接口
let that = this
this.getUserIP(function (ip) { // 调用ip接口
that.ip = String(ip)
that.$http({
method: 'post',
url: url,
params: {
ip: that.ip
}
}).then(({data}) => { // 成功之后调用initWebSocket
that.initWebSocket() // 调用ws
// console.log(data)
})
})
获取到相应的数据之后进行下一步操作
更多推荐
已为社区贡献3条内容
所有评论(0)