3 วิธี Redirect ใน JavaScript
ทั้ง 3 วิธีทำเป้าหมายเดียวกันคือเปลี่ยน URL ที่ผู้ใช้เห็น แต่แตกต่างในการจัดการ History Stack
1. window.location (หรือ window.location.href)
window.location = "https://example.com"; // หรือ window.location.href = "https://example.com";
เพิ่มหน้าใหม่เข้า History Stack → กดปุ่ม Back กลับได้
2. window.location.assign()
window.location.assign("https://example.com");
ทำงานเหมือนข้อ 1 เพิ่มเข้า History Stack
3. window.location.replace()
window.location.replace("https://example.com");
**แทนที่** หน้าปัจจุบันใน History Stack → **กด Back ไม่กลับได้** ใช้สำหรับ Redirect หลัง Login/Logout
Redirect ไปหน้าอื่นในเว็บเดียวกัน
window.location.pathname = '/newpage.html';
ตัวอย่างฟังก์ชันจัดการคลิก
const handleClick = (e) => {
console.log("click");
window.location.replace('https://careerkarma.com');
};
สรุป
- ต้องการให้ผู้ใช้ **กลับได้** → ใช้
location.hrefหรือassign() - ต้องการ **ไม่ให้กลับได้** (เช่นหลัง Login) → ใช้
replace()