2019-07-05

2019-07-05  本文已影响0人  1263536889

[js获取ip地址,操作系统,浏览器版本等信息,可兼容

这次呢,说一下使用js获取用户电脑的ip信息,刚开始只是想获取用户ip,后来就顺带着获取了操作系统和浏览器信息。

先说下获取用户ip地址,包括像ipv4,ipv6,掩码等内容,但是大部分都要根据浏览器的支持情况来决定,目前主流浏览器对于ipv4的支持是统一的。第一种:用于仅支持IE的且允许Activex运行,利用ActiveObject来获取。这种的话可以选择性使用。第二种:利用其它平台的接口,在自己程序中使用如:新浪,太平洋等的接口,来给用户返回ip地址,这种是不太安全的方式,万一人家改变接口了呢?第三种(也是我采用的方式):使用WebRTC(Web Real-Time Communications),他的定义是一项实时通讯技术,它允许网络应用或者站点,在不借助中间媒介的情况下,建立浏览器之间点对点(Peer-to-Peer)的连接,实现视频流和(或)音频流或者其他任意数据的传输。当然这些信息和基本api在MDN上面是可以查看的。我们可以使用WebRTC获取ip地址,经测试,在chrome,opera,firefox,safari均可正常获取,对于IE和Edge,可以采用第一种方式进行兼容。下面是获取代码(我这里没有支持IE/Edge):
const getUserIP = onNewIP => {
// onNewIp - your listener function for new IPs
// Firefox和Chrome的兼容性
const MyPeerConnection = window.RTCPeerConnection || window.mozRTCPeerConnection || window.webkitRTCPeerConnection;
const pc = new MyPeerConnection({
iceServers: [],
});
const noop = () => {};
const localIPs = {};
const 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(
sdp => {
sdp.sdp.split('\n').forEach(line => {
if (line.indexOf('candidate') < 0) return;
line.match(ipRegex).forEach(iterateIP);
});
pc.setLocalDescription(sdp, noop, noop);
},
sdp => sdp,
);
} catch (err) {
return err;
}
// listen for candidate events
pc.onicecandidate = ice => {
if (!ice || !ice.candidate || !ice.candidate.candidate || !ice.candidate.candidate.match(ipRegex)) return;
ice.candidate.candidate.match(ipRegex).forEach(iterateIP);
};
};
export default getUserIP;

其次是获取操作系统,浏览器信息:这里到没有那么麻烦,我使用了包含浏览器信息的Navigator对象,这个对象虽然没有公开标准,但是所有的浏览器都支持他,这就好办了。我们主要用到的是useragent属性,他包含了这些信息,我们要做的只是使用正则表达式分离和提取,针对不同的浏览器,兼容chrome,firefox,opera,ie,edge,safari等,对于其他浏览器,例如360极速等,会返回相应内核对应的浏览器名称。也可以再进行其他判断。下面是代码:
export const getOsInfo = () => {
const userAgent = navigator.userAgent.toLowerCase();
let name = 'Unknown';
let version = 'Unknown';
if (userAgent.indexOf('win') > -1) {
name = 'Windows';
if (userAgent.indexOf('windows nt 5.0') > -1) {
version = 'Windows 2000';
} else if (userAgent.indexOf('windows nt 5.1') > -1 || userAgent.indexOf('windows nt 5.2') > -1) {
version = 'Windows XP';
} else if (userAgent.indexOf('windows nt 6.0') > -1) {
version = 'Windows Vista';
} else if (userAgent.indexOf('windows nt 6.1') > -1 || userAgent.indexOf('windows 7') > -1) {
version = 'Windows 7';
} else if (userAgent.indexOf('windows nt 6.2') > -1 || userAgent.indexOf('windows 8') > -1) {
version = 'Windows 8';
} else if (userAgent.indexOf('windows nt 6.3') > -1) {
version = 'Windows 8.1';
} else if (userAgent.indexOf('windows nt 6.2') > -1 || userAgent.indexOf('windows nt 10.0') > -1) {
version = 'Windows 10';
} else {
version = 'Unknown';
}
} else if (userAgent.indexOf('iphone') > -1) {
name = 'Iphone';
} else if (userAgent.indexOf('mac') > -1) {
name = 'Mac';
} else if (
userAgent.indexOf('x11') > -1 ||
userAgent.indexOf('unix') > -1 ||
userAgent.indexOf('sunname') > -1 ||
userAgent.indexOf('bsd') > -1
) {
name = 'Unix';
} else if (userAgent.indexOf('linux') > -1) {
if (userAgent.indexOf('android') > -1) {
name = 'Android';
} else {
name = 'Linux';
}
} else {
name = 'Unknown';
}
const os = {};
os.name = name;
os.version = version;
/*
//document.write("系统:" + os.name + "版本:" + os.name)
/
return os;
};
export const getBrowerInfo = () => {
const Browser = (window => {
const { document, navigator } = window;
const agent = navigator.userAgent.toLowerCase();
/

//IE8+支持.返回浏览器渲染当前文档所用的模式
//IE6,IE7:undefined.IE8:8(兼容模式返回7).IE9:9(兼容模式返回7||8)
//IE10:10(兼容模式7||8||9)
/
const IEMode = document.documentMode;
// chorme
const chrome = window.chrome || false;
const System = {
agent,
isIE: /trident/.test(agent),
isGecko: agent.indexOf('gecko') > 0 && agent.indexOf('like gecko') < 0,
isWebkit: agent.indexOf('webkit') > 0,
isStrict: document.compatMode === 'CSS1Compat',
supportSubTitle: () => 'track' in document.createElement('track'),
supportScope: () => 'scoped' in document.createElement('style'),
ieVersion: () => {
const rMsie = /(msie\s|trident.
rv:)([\w.]+)/;
const ma = window.navigator.userAgent.toLowerCase();
const match = rMsie.exec(ma);
try {
return match[2];
} catch (e) {
// console.log("error");
return IEMode;
}
},
// Opera版本号
operaVersion: () => {
try {
if (window.opera) {
return agent.match(/opera.([\d.]+)/)[1];
}
if (agent.indexOf('opr') > 0) {
return agent.match(/opr/([\d.]+)/)[1];
}
} catch (e) {
// console.log("error");
return 0;
}
},
};
try {
// 浏览器类型(IE、Opera、Chrome、Safari、Firefox) // safari也提供了专门的判定方式
if (System.isIE) {
System.type = 'IE';
System.version = System.ieVersion();
} else if (window.opera || agent.indexOf('opr') > 0) {
System.type = 'Opera';
System.version = System.operaVersion();
} else if (agent.indexOf('chrome') > 0) {
System.type = 'Chrome';
[, System.version] = agent.match(/chrome/([\d.]+)/);
} else if (window.openDatabase) {
System.type = 'Safari';
[, System.version] = agent.match(/version/([\d.]+)/);
} else if (agent.indexOf('firefox') > 0) {
System.type = 'Firefox';
[, System.version] = agent.match(/firefox/([\d.]+)/);
} else {
System.type = 'unknow';
System.version = 'unknow';
}
// 浏览器外壳
System.shell = () => {
if (agent.indexOf('edge') > 0) {
System.version = agent.match(/edge/([\d.]+)/)[1] || System.version;
return 'edge浏览器';
}
// 遨游浏览器
if (agent.indexOf('maxthon') > 0) {
System.version = agent.match(/maxthon/([\d.]+)/)[1] || System.version;
return '傲游浏览器';
}
// QQ浏览器
if (agent.indexOf('qqbrowser') > 0) {
System.version = agent.match(/qqbrowser/([\d.]+)/)[1] || System.version;
return 'QQ浏览器';
}

    // 搜狗浏览器
    if (agent.indexOf('se 2.x') > 0) {
      return '搜狗浏览器';
    }

    // Chrome:也可以使用window.chrome && window.chrome.webstore判断
    if (chrome && System.type !== 'Opera') {
      const external = window.external;
      const clientInfo = window.clientInformation;
      // 客户端语言:zh-cn,zh.360下面会返回undefined
      const clientLanguage = clientInfo.languages;
      // 猎豹浏览器:或者agent.indexOf("lbbrowser")>0
      if (external && 'LiebaoGetVersion' in external) {
        return '猎豹浏览器';
      }
      // 百度浏览器
      if (agent.indexOf('bidubrowser') > 0) {
        System.version = agent.match(/bidubrowser\/([\d.]+)/)[1] || agent.match(/chrome\/([\d.]+)/)[1];
        return '百度浏览器';
      }
      // 360极速浏览器和360安全浏览器
      if (System.supportSubTitle() && typeof clientLanguage === 'undefined') {
        // object.key()返回一个数组.包含可枚举属性和方法名称
        const storeKeyLen = Object.keys(chrome.webstore).length;
        // const v8Locale = 'v8Locale' in window;
        return storeKeyLen > 1 ? '360极速浏览器' : '360安全浏览器';
      }
      return 'Chrome';
    }
    return System.type;
  };
  // 浏览器名称(如果是壳浏览器,则返回壳名称)
  System.name = System.shell();
  // 对版本号进行过滤过处理
  // System.version = System.versionFilter(System.version);
} catch (e) {
  console.log(e.message);
}
return {
  client: System,
};

})(window);
if (Browser.client.name === undefined || Browser.client.name === '') {
Browser.client.name = 'Unknown';
Browser.client.version = 'Unknown';
} else if (Browser.client.version === undefined) {
Browser.client.version = 'Unknown';
}
/*
document.write(Browser.client.name + " " + Browser.client.version);
*/
return Browser;
};

上一篇下一篇

猜你喜欢

热点阅读