window.location 對象用于獲得目前頁面的位址 (URL),并把浏覽器重定向到新的頁面。
window.location 對象在編寫時可不使用 window 這個字首。
一些例子:
一些執行個體:
location.hostname 傳回 web 主機的域名
location.pathname 傳回目前頁面的路徑和檔案名
location.port 傳回 web 主機的端口 (80 或 443)
location.protocol 傳回所使用的 web 協定(http: 或 https:)
location.href 屬性傳回目前頁面的 URL。
傳回(目前頁面的)整個 URL:
<script>
document.write(location.href);
</script>
以上代碼輸出為:
location.pathname 屬性傳回 URL 的路徑名。
傳回目前 URL 的路徑名:
document.write(location.pathname);
location.assign() 方法加載新的文檔。
加載一個新的文檔:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>菜鳥教程(runoob.com)</title>
function newDoc(){
window.location.assign("https://www.runoob.com")
}
</head>
<body>
<input type="button" value="加載新文檔" onclick="newDoc()">
</body>
</html>