Các phương pháp
| Phương pháp | Hành vi | History |
window.location.href = url | Điều hướng, thêm entry history | Có (Back được) |
window.location.assign(url) | Giống href | Có |
window.location.replace(url) | Thay thế entry hiện tại | Khô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.