2022-06-03 11:10:14
在 JavaScript 中,获取域名的方法主要有两种,具体如下:
1. 使用 window.location.hostname对于 URL
对于 URL
环境限制:
window.location.hostname 仅在浏览器环境中可用。
document.domain 在一些浏览器中可能受到同源策略的限制。
iframe 和 postMessage 的影响:
如果页面使用 iframe,window.location.hostname 返回的是 iframe 中的域名,而不是主页面中的域名。
如果页面使用 postMessage API,document.domain 返回的是发送消息的域。