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

วิธีเปลี่ยนเส้นทางเว็บเพจด้วย JavaScript (Redirect)

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>

สรุปวิธี Redirect ด้วย JavaScript

  1. window.location.href = "url" – วิธีพื้นฐาน มี history
  2. window.location.assign("url") – เหมือน href แต่เป็นเมธอด มี history
  3. window.location.replace("url") – แทนที่หน้าปัจจุบัน ไม่มี history (ไม่กลับได้ด้วยปุ่ม Back)

ตัวอย่าง Redirect ทันที (ไม่ต้องกดปุ่ม)

<script>
  // Redirect ทันที ไม่มี history
  window.location.replace("https://www.example.com");
</script>

ตัวอย่าง Redirect มีเงื่อนไข

<script>
  if (!localStorage.getItem('visited')) {
    localStorage.setItem('visited', 'true');
    window.location.href = "/welcome.html";
  }
</script>

ข้อควรพิจารณา: JavaScript redirect ทำงานเฉพาะเมื่อ browser เปิด JS Server-side redirect (301/302) ดีกว่าสำหรับ SEO