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

Cách dùng window.location redirect URL trong JavaScript

Các phương pháp

Phương phápHành viHistory
window.location.href = urlĐiều hướng, thêm entry historyCó (Back được)
window.location.assign(url)Giống hrefCó
window.location.replace(url)Thay thế entry hiện tạiKhông (Back không về trang cũ)
window.location.reload()Tải lại trang hiện tại-

Ví dụ: Redirect có nút bấm

<!DOCTYPE html>
<html>
<head>
  <script>
    function redirect() {
      window.location.assign("https://www.tutorialspoint.com");
    }
  </script>
</head>
<body>
  <p>Click de chuyen den trang chu.</p>
  <button onclick="redirect()">Redirect Me</button>
</body>
</html>

Redirect tự động (meta refresh thay thế)

<meta http-equiv="refresh" content="5;url=https://example.com">

Lưu ý bảo mật

  • Không redirect dựa trên user input không validate (Open Redirect vulnerability).
  • Whitelist domain cho phép redirect.
  • Dùng replace() cho login/logout flow.