Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> JavaScript

Xóa hash khỏi URL (window.location) không reload trang trong JavaScript

Dùng history.replaceState() — thay đổi URL hiện tại **không load lại trang** và **không thêm history entry**.

Cách làm

history.replaceState(null, null, ' '); // xóa hash, giữ path
// hoặc
history.replaceState(null, null, window.location.pathname + window.location.search);

Giải thích

  • Tham số 1: state object (null = không cần).
  • Tham số 2: title (bỏ qua bởi browser).
  • Tham số 3: url — URL mới relative to origin.

So sánh

  • location.hash = '' → thêm history entry (back button sẽ về hash cũ).
  • history.pushState(null, null, ' ') → thêm history entry mới.
  • history.replaceState(null, null, ' ') → **thay thế entry hiện tại**, không thêm history — **khuyên dùng**.

Lưu ý: Chỉ làm được trên same-origin. Không thể xóa hash cross-origin iframe.