JavaScript 位置對像簡介
在 JavaScript 中,window.location
只讀屬性返回 Location
對象,表示正在該窗口中顯示的文檔的當前 URL。
Location
對象可用於獲取當前頁面 URL、導航到新頁面、重新加載當前頁面、獲取 URL 的不同部分(主機名、協議等)等等。
下面的例子演示瞭如何將 window.location.href
屬性可以用來獲取當前網頁的整個URL:
const url = window.location.href;
console.log(url);
// https://attacomsian.com/blog/javascript-location-object/
同樣,您可以使用 Location
的其他屬性 host
等對象 , hostname
, port
, protocol
, pathname
, search
, 和 hash
訪問 URL 的不同部分:
// Get hostname with port (localhost or localhost:8080)
console.log(location.host);
// Get hostname (localhost or www.domain.com)
console.log(location.hostname);
// Get protocol (http or https)
console.log(location.protocol);
// Get port number (8080)
console.log(location.port);
// Get pathname (/javascript-tutorials/)
console.log(location.pathname);
// Get query string (?q=object)
console.log(location.search);
// Get URL fragment identifier (#trending)
console.log(window.location.hash);
除了上面提到的屬性,Location
object 還提供了 assign()
等幾種方法 , reload()
, 和 replace()
操作當前 URL:
// Load new URL
location.assign(`https://attacomsian.com`);
// Reload the current URL
location.reload();
// Load new URL with session history
location.replace(`https://youtube.com`);
// Print complete URL (same as location.href)
location.toString();