Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> JavaScript

Redirect ผู้เยี่ยมชมไปหน้า/เว็บอื่น ด้วย JavaScript window.location

เรียนรู้วิธีและเหตุผล redirect ผู้เยี่ยมชมไป URL อื่น ด้วย window.location object

วิธี Page Redirect

Redirect ไป URL ใหม่ ต้อง execute JS นี้บนหน้าที่ต้องการ redirect:

window.location = "https://wheretoredirect.com";

ใส่ใน external .js file หรือ inline ใน <head>:

<script type="text/javascript">
  window.location = "https://wheretoredirect.com";
</script>

ผู้เยี่ยมชมที่ไป https://yourwebsite.com จะถูก redirect ทันที

Use cases:

  • Domain ใหม่ (oldsite.com → newsite.com)
  • หน้า/โพสต์ต่าง domain เดียวกัน
  • Subfolder (yourwebsite.com/archive)
  • Subdomain (support.yourdomain.com)

ใช้ protocol ให้ถูกต้อง (https, www, https://www)

แสดงข้อความก่อน Redirect

เพิ่ม UX ด้วยข้อความแจ้งและ countdown timer:

function showMessageBeforeRedirect() {
  window.location = "https://wheretoredirect.com";
}
document.write("You'll be redirected to our new domain in 5 seconds :-)");
setTimeout("showMessageBeforeRedirect()", 5000);

5000 = milliseconds (5 วินาที)

ทำไมต้อง Redirect?

  • เปลี่ยน domain ใหม่ ต้องการให้ผู้ใช้เก่าไป domain ใหม่
  • มีหลาย version เว็บ (legacy vs modern) redirect ให้ตรง browser
  • หลายภาษา redirect ตาม language settings (เช่น /it สำหรับ Italian)