Page redirection: คลิก URL หน้า X แต่ถูกนำไปหน้า Y ทำได้ง่ายด้วย JavaScript ฝั่งไคลเอนต์
ตัวอย่าง: Redirect ไปหน้าแรก
<html>
<head>
<script>
function Redirect() {
window.location.assign("https://www.tutorialspoint.com");
}
</script>
</head>
<body>
<p>Click the following button, you will be redirected to home page.</p>
<input type="button" value="Redirect Me" onclick="Redirect();" />
</body>
</html>
วิธีต่างๆ ของ JavaScript Redirect
| โค้ด | คำอธิบาย | History |
|---|---|---|
window.location.href = "url" | กำหนด URL ใหม่ | มี (Back ได้) |
window.location.assign("url") | โหลดเอกสารใหม่ | มี (Back ได้) |
window.location.replace("url") | แทนที่เอกสารปัจจุบัน | ไม่มี (Back ไม่ได้) |
Redirect ทันที (Immediate)
<script>
window.location.replace("https://www.example.com");
</script>
Redirect หลังหน่วงเวลา
<script>
setTimeout(function() {
window.location.href = "https://www.example.com";
}, 3000); // 3 วินาที
</script>
แนะนำ: ใช้ Server-side redirect (HTTP 301/302) สำหรับ SEO และประสิทธิภาพ JavaScript redirect ใช้กรณีต้องการ logic เงื่อนไข (เช่น login check, A/B testing)