本文內容相當簡單,為大家整理一些在 JavaScript 中取得當前頁面網址相關資訊的常用指令,方便日後查閱。
console.info("document.URL=" + document.URL);
console.info("document.location.href=" + document.location.href);
//console.info("document.base=" + document.base); //這是錯的!
console.info("document.location=" + document.location);
console.info("self.location.href=" + self.location.href);
console.info("top.location.href=" + top.location.href);
console.info("location.hostname=" + location.hostname);
console.info("window.location.host=" + window.location.host);
console.info("window.location.pathname=" + window.location.pathname);
透過這些屬性,我們可以取得完整網址(URL、href)、主機名稱(hostname)、主機與連接埠(host)以及路徑(pathname)等資訊;其中 top.location 可用於取得最上層視窗的網址。暫時想到的就這些,後續再補充更新。