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

วิธีใช้ window.location เปลี่ยนเส้นทาง (Redirect) ไปยัง URL อื่น

คุณอาจเคยคลิก URL เพื่อไปหน้า X แต่ถูกนำไปหน้า Y แทน เกิดจาก Page Redirection (การเปลี่ยนเส้นทางหน้า)

ทำได้ง่ายด้วย JavaScript ฝั่งไคลเอนต์ (client-side) เพิ่มบรรทัดเดียวในส่วน head

ตัวอย่าง: Redirect ไปหน้าแรก Tutorialspoint

<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>

เมธอด window.location สำหรับ Redirect

เมธอด/พรอเพอร์ตี้คำอธิบายความแตกต่าง
window.location.href = "url"กำหนด URL ใหม่ (พรอเพอร์ตี้)พรอเพอร์ตี้ พร้อม history
window.location.assign("url")โหลดเอกสารใหม่ (เมธอด)มี history ย้อนกลับได้
window.location.replace("url")แทนที่เอกสารปัจจุบันไม่มี history (ไม่กลับได้ด้วยปุ่ม Back)
window.location.reload()โหลดหน้าซ้ำ-

Redirect ทันทีเมื่อโหลดหน้า

<script>
  window.location.replace("https://www.example.com");
</script>

หมายเหตุ: Redirect ฝั่งเซิร์ฟเวอร์ (HTTP 301/302) ดีกว่าสำหรับ SEO และประสิทธิภาพ