在JavaScript中获取URL地址通常指的是获取当前浏览器窗口或标签页中显示的网页的完整URL。以下是一些基础概念和相关方法:
JavaScript提供了多种方式来获取当前页面的URL。
window.location.href
这是最常用的方法,可以直接获取整个URL字符串。
let currentUrl = window.location.href;
console.log(currentUrl); // 输出完整的URL
document.URL
这个属性与 window.location.href
类似,也可以获取完整的URL。
let currentUrl = document.URL;
console.log(currentUrl); // 输出完整的URL
如果你需要获取URL的不同部分(如协议、主机名、路径等),可以使用 window.location
对象的其他属性。
let protocol = window.location.protocol; // http: 或 https:
let hostname = window.location.hostname; // www.example.com
let pathname = window.location.pathname; // /path/to/page.html
let search = window.location.search; // ?query=string
let hash = window.location.hash; // #section1
DOMContentLoaded
事件。document.addEventListener('DOMContentLoaded', function() {
let currentUrl = window.location.href;
console.log(currentUrl);
});
通过上述方法和注意事项,你应该能够在JavaScript中有效地获取和处理URL地址。
领取专属 10元无门槛券
手把手带您无忧上云