| 方法 | 行為 | 適用場景 |
|---|---|---|
location.href = url | 當前頁面跳轉,保留歷史記錄 | 一般頁面導航 |
location.replace(url) | 當前頁面跳轉,不保留歷史記錄 | 登入後跳轉、防止返回鍵回登入頁 |
location.assign(url) | 同 href,保留歷史 | 功能同 href,較少用 |
window.open(url, '_blank') | 新分頁/視窗開啟 | 外部連結、檔案預覽 |
window.open(url, '_self') | 當前視窗開啟 | 同 location.href |
history.back() | 返回上一頁 | 返回按鈕 |
history.go(-n) | 返回 n 頁 | 多步驟流程返回 |
// 1. 一般跳轉(保留歷史)
location.href = "https://www.example.com";
location.href = "page.aspx?id=123";
// 2. 替換跳轉(不保留歷史,無法按返回鍵回來)
location.replace("https://www.example.com");
// 3. 相對路徑跳轉
location.href = "../list.aspx";
location.href = "/products/detail/456";
// 4. 攜帶查詢參數
var params = "?keyword=" + encodeURIComponent(searchText) + "&page=1";
location.href = "search.aspx" + params;
// 基本新視窗
window.open("https://www.example.com", "_blank");
// 指定視窗特性(寬高、位置、工具列等)
var features = "width=800,height=600,top=100,left=200," +
"menubar=no,toolbar=no,location=no,status=no," +
"scrollbars=yes,resizable=yes";
window.open("report.aspx?id=123", "reportWin", features);
// 獲取視窗參考,便於後續控制
var popup = window.open("chat.html", "chatWindow", "width=400,height=500");
if (popup) {
popup.focus(); // 聚焦視窗
// 監聽關閉事件
var checkClosed = setInterval(function() {
if (popup.closed) {
clearInterval(checkClosed);
console.log("彈出視窗已關閉");
}
}, 500);
}
$.extend({
navigate: {
// 一般跳轉
to: function(url) {
location.href = url;
},
// 替換跳轉
replace: function(url) {
location.replace(url);
},
// 新視窗開啟
popup: function(url, name, options) {
var defaults = { width: 800, height: 600 };
var opts = $.extend({}, defaults, options);
var features = Object.keys(opts).map(function(k) {
return k + "=" + opts[k];
}).join(",");
return window.open(url, name || "_blank", features);
},
// 返回上一頁
back: function(steps) {
history.go(-(steps || 1));
},
// 重新整理
reload: function(force) {
location.reload(force || false);
}
}
});
// 使用範例
$.navigate.to("list.aspx");
$.navigate.replace("dashboard.aspx");
$.navigate.popup("print.aspx?id=1", "printWin", { width: 600, height: 800 });
| 問題 | 原因 | 解決方案 |
|---|---|---|
| 跳轉被瀏覽器攔截 | 非使用者主動觸發的 window.open | 確保在 click 事件中呼叫,或引導使用者允許彈出 |
| 中文參數亂碼 | URL 編碼問題 | 使用 encodeURIComponent() 編碼參數值 |
| iframe 中跳轉頂層 | 預設僅跳轉 iframe 內部 | 使用 top.location.href = url 或 parent.location.href = url |
| 表單提交後跳轉 | 同步提交導致頁面離開 | 使用 AJAX 提交,success 回呼中跳轉 |
現代框架(Vue Router、React Router、Angular Router)使用 History API:
// HTML5 History API 原生用法
history.pushState({page: 1}, "標題", "/page/1"); // 新增歷史記錄
history.replaceState({page: 2}, "標題", "/page/2"); // 替換當前記錄
// 監聽瀏覽器前進後退
window.addEventListener('popstate', function(event) {
console.log('路由變更:', event.state);
});
location.href 是最常用的跳轉方式,location.replace() 適合登入後導向避免返回登入頁,window.open() 適用新視窗需求。實務開發建議封裝統一導航工具,處理編碼、攔截、SPA 路由等跨專案共性問題。