vue获取本机ip地址
需求是通过前端获取本机ip地址传到后端记录
在页面data中定义变量
data() {
return {
localIPAddress:'',//ip
}
},
method中定义获取ip函数
//前端获取本地ip
getUserIP (onNewIP) {
let MyPeerConnection = window.RTCPeerConnection || window.mozRTCPeerConnection || window.webkitRTCPeerConnection;
let pc = new MyPeerConnection({
iceServers: []
});
let noop = () => {
};
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;
let iterateIP = (ip) => {
if (!localIPs[ip]) onNewIP(ip);
localIPs[ip] = true;
};
pc.createDataChannel('');
pc.createOffer().then((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((reason) => {
});
pc.onicecandidate = (ice) => {
if (!ice || !ice.candidate || !ice.candidate.candidate || !ice.candidate.candidate.match(ipRegex)) return;
ice.candidate.candidate.match(ipRegex).forEach(iterateIP);
};
},
测试控制台打印
如果获取不到可能是浏览器版本过高,修改步骤如下。
1.打开谷歌浏览器,地址栏输入chrome://flags,进入。
2.搜索Anonymize local IPs exposed by WebRTC,将其设置为Disabled。
mounted() {
this.getUserIP((ip) => {
this.localIPAddress = ip;
console.log("ip-----------"+this.localIPAddress)
});
//禁止浏览器后退
history.pushState(null, null, document.URL);
window.addEventListener('popstate', function () {
history.pushState(null, null, document.URL);
})
},