客户端js取得页面域名的两个途径对比
发布于 作者:苏南大叔 来源:程序如此灵动~

在书写js
代码的时候,常常有需求,需要获得当前js
运行环境的网址的域名。那么就会有几种写法,通常来说,着几种写法都是等同的,会返回一致的值。但是,偶然间,苏南大叔发现,其实,他们之前还是有所差别的。
苏南大叔在本文中,对比两个常见的客户端js
语句。这里说客户端,就是针对node
来说的。本文说的仅仅是最普通常见的运行在浏览器里面的js
。
方案预览
99.9%的情况下,下面三条语句是等同的。
document.domain;
window.location.host;
window.location.hostname;
特殊情况
在网络错误的情况下,三条语句开始发生了微妙的变化。
这种错误页面下,请看不同的返回值。
分解window.location
window.location
可以分解出很多内容。
对于url https://newsn.net/about.html?aaa=bbb#123
,window.location
信息分解如下:
hash : "#123"
host : "newsn.net"
hostname : "newsn.net"
href : "https://newsn.net/about.html?aaa=bbb#123"
origin : "https://newsn.net"
pathname : "/about.html"
port: ""
protocol: "https:"
search:"?aaa=bbb"
值得注意的几点是:
- hash带
#
- pathname 带
/
- search 带
?
- port为空
总结
document.domain
必须是正常的页面,才能成立,否则为空。window.location
恒定有效。但是页面异常的时候,分解的url并非显示在地址栏中的那一个。
感谢您的阅读,如果想继续阅读js
相关经验文章。请点击苏南大叔的相关链接。


