通过JavaScript实现获取地址栏中的各类信息

有时候我们需要借助JavaScript来获取地址栏中的ip,端口号或者应用名等信息,这个时候就需要使用各类方法组合出最终想要的结果。

一、web服务的地址格式

协议+ip+port+应用名,例如http://180.26.26.12:8080/webService

二、逐一获取

若我想获取应用名之前协议+ip+port的信息,则可以按照以下方式获取:

// http://180.26.26.12:8080
var fontUrl = window.location.origin;

若我想获取其中的应用名“demo”,则可以用以下代码实现。无论带不带应用名都没有影响

// webService
var webApp = (window.location.pathname).split('/')[1];

只获取网络协议:

// http
var protocol = window.location.protocol;

获取ip+port:

// 180.26.26.12:8080
var domainPort = window.location.host;

所以,我们要用js拼接完整网页应用的地址,可以用以下两种方式:

function getUrl(){
	var protocol = window.location.protocol;
	var domainPort = window.location.host;
	var webApp = (window.location.pathname).split('/')[1];
	var url = protocol + "//" + domainPort + "/" + webApp;
	return url
}

或者

function getUrl(){
	var webApp = (window.location.pathname).split('/')[1];
	var url = window.location.origin + "/" + webApp + "/";
	return url;
}

参考资料:
js 获取请求网络协议、IP、端口号、项目名称

发布了58 篇原创文章 · 获赞 91 · 访问量 34万+

猜你喜欢

转载自blog.csdn.net/imVainiycos/article/details/100186524
今日推荐