在瀏覽器環境中,window.location 與 window.history 是兩個經常用來處理頁面網址與瀏覽歷史的物件。前者負責讀取與導向網址,後者則負責前後頁操作。
location 物件可以取得目前頁面的網址資訊,也可以用來跳轉到其他頁面。撰寫時通常可以省略 window 前綴。
console.log(location.href);
console.log(location.hostname);
console.log(location.pathname);
console.log(location.protocol);
若要載入新的文件,可以使用 location.assign(),也可以直接設定 location.href:
location.assign('https://www.example.com');
// 等價寫法
location.href = 'https://www.example.com';
history 物件提供瀏覽歷史操作。为了保护使用者隱私,JavaScript 對部分歷史操作設有限制,但常見的前後頁功能仍可正常使用。
history.back();
history.forward();
history.go(-1);
history.back() 等同於點擊瀏覽器上一頁,history.forward() 等同於點擊下一頁。在實際開發中,這類 API 常用於自訂導覽按鈕或表單流程控制。