window.location 物件用於取得當前頁面的位址(URL),並可把瀏覽器重新導向到新頁面。撰寫時可以省略 window 這個前綴。
location.hostname 回傳 web 主機的域名
location.pathname 回傳當前頁面的路徑和檔案名
location.port 回傳 web 主機的連接埠(80 或 443)
location.protocol 回傳所使用的 web 協定(https:// 或 https://)
location.href 屬性回傳當前頁面的 URL,範例如下:
<script> document.write(location.href); </script>
回傳目前 URL 的路徑名:
<script> document.write(location.pathname); </script>
location.assign() 方法用於載入新的文件:
<html>
<head>
<script>
function newDoc()
{
window.location.assign("https://hovertree.com/texiao/js/6.htm")
}
</script>
</head>
<body>
<input type="button" value="載入新文件" onclick="newDoc()">
</body>
</html>
透過這些屬性與方法,就能靈活取得與操作目前頁面的 URL 資訊。