BOM Location

window.location 对象是 Location 接口的实例,表示当前页面地址 (URL) 。

window.location 对象是 Location 接口的实例,表示当前页面地址 (URL) 。

window.location 对象可以省略 window 前缀。

一些例子:

  • window.location.href 返回当前页面的 uURL
  • window.location.hostname 返回网络主机的域名
  • window.location.pathname 返回当前页面的路径和文件名
  • window.location.protocol 返回使用的网络协议(http:https:
  • window.location.assign() 加载新文档

窗口位置 Href

window.location.href 属性返回当前页面的 URL。

显示当前页面的 href(URL):

document.getElementById("demo").innerHTML = "Page location is " + window.location.href;

结果是: Page location is https://www.gobeta.net/tutorials/javascript/bom-location

主机名

window.location.hostname 属性返回网址中的主机名。

显示主机名:

document.getElementById("demo").innerHTML = "Page hostname is " + window.location.hostname;

结果是:Page hostname is www.gobeta.net

路径

window.location.pathname 属性返回当前页面的路径。

显示当前 URL 的路径名:

document.getElementById("demo").innerHTML = "Page path is " + window.location.pathname;

结果是: Page path is /tutorials/javascript/bom-location

协议

window.location.protocol 属性返回页面的 Web 协议。

显示网络协议:

document.getElementById("demo").innerHTML = "Page protocol is " + window.location.protocol;

结果是: Page protocol is https:

端口

window.location.port 属性返回(当前页面的)互联网主机端口号。

显示主机名:

document.getElementById("demo").innerHTML = "Port number is " + window.location.port;

结果是: Port number is

大多数浏览器不会显示默认端口号(http 为 80,https 为 443

加载新页面

window.location.assign() 方法加载一个新文档。

加载一个新文档:

<html>
  <head>
    <script>
      function newDoc() {
        window.location.assign("https://www.gobeta.net");
      }
    </script>
  </head>
  <body>
    <input type="button" value="Load new document" onclick="newDoc()" />
  </body>
</html>