Có vài cách redirect trang web: client-side dùng meta tag HTML, server-side dùng HTTP redirect. Bài này xem cách redirect dùng JavaScript.
Hai phương pháp
Có hai cách dùng JS cho page redirection. Cả hai liên quan đến window location object.
1. location.href
Cách đầu dùng property href trên location object (thuộc window object). Chỉ cần gán URL muốn redirect vào location.href. Làm trong hàm JS chạy khi trang load:
<html>
<head>
<style>
body { font-family: 'Roboto'; margin: 20px; }
p { margin: 0; padding: 0; }
</style>
</head>
<body onload="handleRedirect('https://www.careerkarma.com/blog/html')">
You are being redirect to <a rel="noreferrer noopener" href="https://careerkarma.com/blog/html">https://www.careerkarma.com/blog/html.</a>
Please click this link if not redirected in five seconds
</body>
<script>
const handleRedirect = (url) => {
location.href = url;
}
</script>
</html>
Thêm script tag cuối document, trước body tag. Nơi JS code. Hàm handleRedirect có tham số url. Gán location.href = url.
Đầu body, event onload chạy hàm JS gán. Ở đây truyền URL muốn redirect. Redirect ngay lập tức đến phần HTML blog Career Karma.
Muốn pause chút trước redirect, dùng setTimeout:
const handleRedirect = (url) => {
setTimeout(() => {
location.href = url;
}, 2000);
}
Mọi thứ khác giữ nguyên.
Phương pháp này thêm trang gốc vào history stack. Truy cập bằng nút back browser. Có phương pháp khác thay URL – xem tiếp!
2. location.replace()
Khác với phương pháp gán URL mới cho property location object, location.replace() là method gán VÀ thay thế URL gốc bằng URL chỉ định.
Phương pháp này KHÔNG đặt URL gốc lên browser stack, nó thay thế destination bằng redirected URL. Cách làm:
<html>
<head>
<style>
body { font-family: 'Roboto'; margin: 20px; }
p { margin: 0; padding: 0; }
</style>
</head>
<body onload="location.replace('https://www.careerkarma.com/blog/html')">
You are being redirect to <a rel="noreferrer noopener" href="https://careerkarma.com/blog/html">https://www.careerkarma.com/blog/html.</a>
Please click this link if not redirected in five seconds
</body>
</html>
Nhìn thấy không cần script tag cho one-liner này. Khi document load, chạy location.replace method, điều hướng đến site trong ngoặc đơn.
Xong! Bây giờ bạn có thể redirect trang web mới dùng JavaScript.