📜  获取站点 url javascript (1)

📅  最后修改于: 2023-12-03 15:27:51.375000             🧑  作者: Mango

获取站点 URL JavaScript

在 JavaScript 中,我们可以使用 window.location 对象获取当前页面的 URL。其中,window.location.href 属性返回当前页面的完整 URL,包括协议、主机、路径和查询参数等。

console.log(window.location.href);
// 输出类似 "http://www.example.com/page.html?query=string" 的字符串

如果你只需要获取当前页面的主机名(即域名),可以使用 window.location.hostname 属性。

console.log(window.location.hostname);
// 输出类似 "www.example.com" 的字符串

如果你需要获取当前页面的路径,则可以使用 window.location.pathname 属性。

console.log(window.location.pathname);
// 输出类似 "/page.html" 的字符串

除此之外,我们还可以使用 window.location.protocolwindow.location.port 属性获取当前页面的协议和端口号。

console.log(window.location.protocol);
// 输出类似 "http:" 的字符串

console.log(window.location.port);
// 输出类似 "80" 或 "8080" 的字符串

最后,我们可以结合上述属性,获取当前页面的站点 URL。

console.log(window.location.protocol + "//" + window.location.hostname + window.location.pathname);
// 输出类似 "http://www.example.com/page.html" 的字符串

以上就是获取站点 URL 的一些简单方法。希望对您有所帮助!