window.location (หรือแค่ location) เป็น Object ที่เก็บข้อมูล URL ปัจจุบัน และมี Method สำหรับ Redirect (เปลี่ยนหน้า) หลายวิธี
Method หลักสำหรับ Redirect
| Method | คำอธิบาย | History |
|---|---|---|
location.href = url | กำหนด href ใหม่ (Common) | เพิ่ม Entry ใหม่ (Back ได้) |
location.assign(url) | โหลดหน้าใหม่ (Standard) | เพิ่ม Entry ใหม่ (Back ได้) |
location.replace(url) | แทนที่หน้าปัจจุบัน | ไม่เพิ่ม Entry (Back ไม่ได้) |
location.reload() | โหลดหน้าปัจจุบันใหม่ | - |
ตัวอย่างโค้ด (ใช้ assign)
<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>
การเลือกใช้งาน
- href / assign: ใช้ทั่วไป User สามารถกด Back กลับมาได้
- replace: ใช้เมื่อ ไม่ต้องการให้ User Back กลับมา (เช่น Login Success → Redirect to Dashboard, Payment Success)
- reload: Refresh หน้าปัจจุบัน
Properties อื่นๆ ของ location
location.href // Full URL: "https://example.com/path?query=1#hash" location.protocol // "https:" location.host // "example.com:443" location.hostname // "example.com" location.port // "443" (หรือ "" ถ้า Default) location.pathname // "/path" location.search // "?query=1" location.hash // "#hash" location.origin // "https://example.com" (Protocol + Host)
Redirect พร้อม Query Parameters
// Manual
location.href = '/search?q=' + encodeURIComponent(query) + '&page=1';
// URLSearchParams (Modern)
const params = new URLSearchParams({ q: query, page: 1 });
location.href = '/search?' + params.toString();
// Relative Redirect
location.href = '../parent-page';
location.href = '/absolute/path';
location.pathname = '/new-path'; // เปลี่ยน Path อย่างเดียว
Security Considerations
- Open Redirect Vulnerability: ไม่ควร Redirect ไป URL จาก User Input โดยไม่ Validate
- Validate Whitelist:
allowedDomains.includes(new URL(url).hostname) - ใช้ Relative Path เมื่อเป็นไปได้
ข้อควรระวัง
location = urlทำงานเหมือนhref = url(แต่ไม่ชัดเจน)- ใน Iframe: ใช้
top.location.hrefเพื่อ Redirect หน้าหลัก - SPA (React/Vue/Angular): ใช้ Router (
router.push()) แทน location โดยตรง