萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

JavaScript 頁面跳轉與開啟新視窗完整指南

核心跳轉方式對照

方法行為適用場景
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);
}

jQuery 封裝跳轉工具函式

$.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 回呼中跳轉

單頁應用 (SPA) 路由跳轉

現代框架(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 路由等跨專案共性問題。

copyright © 萬盛學電腦網 all rights reserved