首先要解除瀏覽器獲取本機IP的安全限制
火狐(FireFox) 刪除隱藏IP
瀏覽器輸入 about:config
搜索配置 media.peerconnection.enabled 改為false ( 刷新程序,IP正常顯示 )
谷歌(Chrome) 刪除隱藏IP
瀏覽器輸入:chrome://flags/#enable-webrtc-hide-local-ips-with-mdns
把 Anonymize local IPs exposed by WebRTC 設置為 disabled ( 刷新程序,IP正常顯示 )文章來源:http://www.zghlxwxcb.cn/news/detail-479252.html
edge瀏覽器刪除隱藏ip
瀏覽器輸入: edge://flags/#enable-webrtc-hide-local-ips-with-mdns
把 Anonymize local IPs exposed by WebRTC 設置為 disabled ( 刷新程序,IP正常顯示 )
備注
1.設置完成后要重啟瀏覽器
2.若沒有查到相對應的設置,請檢查瀏覽器版本更新文章來源地址http://www.zghlxwxcb.cn/news/detail-479252.html
methods方法
// 獲取ip地址
getUserIP(onNewIP) {
console.log('獲取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中調(diào)用獲取IP的方法
var _that = this
this.getUserIP(function(ip){
console.log("得到的本地IP :" + ip) // 得到的本地IP :192.168.21.23
console.log(_that.loginForm)
_that.loginForm.userIP = ip //這里不能用this 因為this指向的是這個回調(diào)函數(shù)的this
})
到了這里,關于vue項目前端獲取本機IP的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關文章,希望大家以后多多支持TOY模板網(wǎng)!