📜  js 获取基本 url - Javascript (1)

📅  最后修改于: 2023-12-03 14:43:33.061000             🧑  作者: Mango

JS获取基本URL - Javascript

在web开发中,有时我们需要获取当前网页的基本URL信息,以方便我们进行一系列操作。这篇文章将介绍如何使用Javascript获取基本URL信息。

window对象

在Javascript中,window对象代表了整个浏览器窗口,我们可以从window对象中获取网页的基本URL信息。

获取当前URL

我们可以使用window对象的location.href属性获取当前网页的URL信息。例如:

const url = window.location.href;
console.log(url);

输出:

"http://example.com/path/to/page.html"
获取当前域名

我们可以使用window对象的location.hostname属性获取当前网页的域名信息。例如:

const domain = window.location.hostname;
console.log(domain);

输出:

"example.com"
获取当前协议

我们可以使用window对象的location.protocol属性获取当前网页的协议信息。例如:

const protocol = window.location.protocol;
console.log(protocol);

输出:

"http:"
获取当前路径

我们可以使用window对象的location.pathname属性获取当前网页的路径信息(不包括域名和协议)。例如:

const path = window.location.pathname;
console.log(path);

输出:

"/path/to/page.html"
获取当前网页完整URL

我们可以使用window对象的location.toString()方法获取当前网页的完整URL信息。例如:

const url = window.location.toString();
console.log(url);

输出:

"http://example.com/path/to/page.html"
总结

通过使用window对象的相关属性和方法,我们可以轻松地获取当前网页的基本URL信息。以上就是本篇文章的全部内容,希望能对你有所帮助。