JS获取本机IP地址的方法(附上解决浏览器无法获取IP的方法)

JavaScript011

JS获取本机IP地址的方法(附上解决浏览器无法获取IP的方法),第1张

获取本机IP地址: if(typeof window != 'undefined'){     var RTCPeerConnection = window.RTCPeerConnection || window.mozRTCPeerConnection || window.webkitRTCPeerConnection     if (RTCPeerConnection) (()=>{         var rtc = new RTCPeerConnection()         rtc.createDataChannel('') //创建一个可以发送任意数据的数据通道         rtc.createOffer( offerDesc => { //创建并存储一个sdp数据         rtc.setLocalDescription(offerDesc)     }, e => { console.log(e)})     rtc.onicecandidate =(evt) => { //监听candidate事件         if (evt.candidate) {             console.log('evt:',evt.candidate)             let ip_rule = /([0-9]{1,3}(\.[0-9]{1,3}){3}|[a-f0-9]{1,4}(:[a-f0-9]{1,4}){7})/             var ip_addr = ip_rule.exec(evt.candidate.candidate)[1]             console.log('ip_addr:',ip_addr)   //打印获取的IP地址         }}     })()     else{console.log("没有找到")} } 如果电脑没获取到,基本上是因为浏览器限制了,解除方法如下: 解决方案: 火狐(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.xxx.com/index.html?ver=1.0&id=6#page1

getQueryVariable(ver)// 1.0

getQueryVariable(id) // 6

我们可以用javascript获得其中的各个部分

1、整个URl字符串(在浏览器中就是完整的地址栏 http://www.xxx.com/index.html?ver=1.0&id=6#page1 )

本例返回值: ( http://www.xxx.com/index.html?ver=1.0&id=6#page1 )

2、URL 的协议部分 ( http://www.xxx.com/index.html?ver=1.0&id=6#page1 )

本例返回值:http:

3、URL 的主机部分 ( http://www.xxx.com/index.html?ver=1.0&id=6#page1 )

本例返回值: www.xxx.com

4、URL 的端口部分 ( http:192.168.1.152:8080/index.html)

如果采用默认的80端口(update:即使添加了:80),那么返回值并不是默认的80而是空字符

本例返回值:"8080"

5、URL 的路径部分( http://192.168.1.145/community/page/index.html?categoryId=#page3 )

本例返回值:/community/page/index.html

6、查询(参数)部分

除了给动态语言赋值以外,我们同样可以给静态页面,并使用javascript来获得相信应的参数值

本例返回值:?ver=1.0&id=6

7、锚点 ( http://192.168.1.145/community/page/index.html?categoryId=#page3 )

本例返回值:#page3

来源于: https://www.cnblogs.com/zhipeng007/p/10673105.html

属性 描述

hash设置或获取 href 属性中在井号“#”后面的分段。

host 设置或获取 location 或 URL 的 hostname 和 port 号码。

hostname 设置或获取 location 或 URL 的主机名称部分。

href 设置或获取整个 URL 为字符串。

pathname 设置或获取对象指定的文件名或路径。

port 设置或获取与 URL 关联的端口号码。

protocol 设置或获取 URL 的协议部分。

search设置或获取 href 属性中跟在问号后面的部分。