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

Redirect ผู้เยี่ยมชมตาม Browser ด้วย JavaScript

เว็บไซต์อาจใช้ modern features ที่ไม่เข้ากับบาง browser (โดยเฉพาะ legacy เช่น IE) ใช้ JS detect browser แล้ว redirect ไป version ที่เข้ากันได้

Redirect ถ้าไม่ได้ใช้ Chrome

สมมติ cutting-edge version ใช้ได้แค่ Chrome ต้อง redirect ผู้ใช้ browser อื่นไป legacy version:

if (!!window.chrome) {
  window.location = "https://yourdomain.com";
} else {
  window.location = "https://yourdomain.com/legacy-version";
}

อาจแจ้งผู้ใช้และแนะนำ Chrome:

if (!!window.chrome) {
  window.location = "https://yourdomain.com";
  alert("You're using Chrome");
} else {
  alert("Our apologies, at the moment you have to use Chrome to use the latest version. You'll be redirected to our legacy website.");
  window.location = "https://yourdomain.com/legacy-site";
}

ลองทดสอบ: เปิด CodePen ใน Chrome แล้วลอง Firefox, Opera

Note: ลบ alert("You're using Chrome") จริงๆ เพราะใส่แค่ demo

Browser detection เปลี่ยนแปลงเร็ว ต้องติดตาม StackOverflow thread นี้