在JavaScript中,获取当前页面的URL可以通过多种方式实现。以下是一些常用的方法:
window
对象代表当前窗口或框架。以下是几种获取当前页面URL的方法:
window.location.href
let currentUrl = window.location.href;
console.log(currentUrl); // 输出完整的URL
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; // 例如 "#section"
console.log("Protocol:", protocol);
console.log("Hostname:", hostname);
console.log("Pathname:", pathname);
console.log("Search:", search);
console.log("Hash:", hash);
通过上述方法,你可以有效地获取和处理当前页面的URL。如果遇到特定问题,可以根据具体情况进行调试和优化。
领取专属 10元无门槛券
手把手带您无忧上云