หัวข้อ 6: Browser APIs เบื้องต้น

คำจำกัดความ

Browser APIs คือชุดความสามารถที่ browser เปิดให้ JavaScript เรียกใช้ เช่น ตำแหน่งผู้ใช้ การแจ้งเตือน clipboard media query และการสังเกต element ใน viewport

%%{init: {"theme": "base", "themeVariables": {"primaryColor": "#458588", "primaryTextColor": "#fbf1c7", "primaryBorderColor": "#fabd2f", "lineColor": "#a89984", "secondaryColor": "#b8bb26", "tertiaryColor": "#d3869b", "background": "#282828", "mainBkg": "#3c3836", "textColor": "#ebdbb2"}}}%%
flowchart TD
  A["Browser APIs
ความสามารถของเบราว์เซอร์"] --> B["Geolocation
ตำแหน่งผู้ใช้"] A --> C["Notification
แจ้งเตือน"] A --> D["Clipboard
คัดลอกข้อความ"] A --> E["matchMedia
ตรวจเงื่อนไข media"] A --> F["IntersectionObserver
สังเกต viewport"]

Geolocation

function getLocation() {
  if (!navigator.geolocation) {
    console.log("เบราว์เซอร์ไม่รองรับ Geolocation");
    return;
  }

  navigator.geolocation.getCurrentPosition(
    position => {
      // อ่าน latitude และ longitude
      const { latitude, longitude } = position.coords;
      console.log(`Lat: ${latitude}, Lng: ${longitude}`);
    },
    error => {
      console.log(`ไม่สามารถอ่านตำแหน่งได้: ${error.message}`);
    }
  );
}

// ตัวอย่างการใช้งาน
getLocation();

Notification

async function showNotification() {
  // ขอสิทธิ์แจ้งเตือน
  const permission = await Notification.requestPermission();

  if (permission === "granted") {
    new Notification("CAI Online", {
      body: "ถึงเวลาเรียนบท DOM แล้ว",
      icon: "/static/icon.png"
    });
  }
}

// ตัวอย่างการใช้งาน
// showNotification();

Clipboard API

async function copyText(text) {
  try {
    // คัดลอกข้อความไปยัง clipboard
    await navigator.clipboard.writeText(text);
    console.log("คัดลอกแล้ว");
  } catch (error) {
    console.log("คัดลอกไม่สำเร็จ", error);
  }
}

// ตัวอย่างการใช้งาน
copyText("https://example.com");

matchMedia

const darkModeQuery = window.matchMedia("(prefers-color-scheme: dark)");

function applyTheme(event) {
  // event.matches เป็น true เมื่อผู้ใช้ตั้งค่า dark mode
  document.documentElement.dataset.theme = event.matches ? "dark" : "light";
}

applyTheme(darkModeQuery);
darkModeQuery.addEventListener("change", applyTheme);

IntersectionObserver

const target = document.querySelector(".lazy-section");

const observer = new IntersectionObserver(entries => {
  entries.forEach(entry => {
    if (entry.isIntersecting) {
      // element เข้ามาใน viewport แล้ว
      entry.target.classList.add("is-visible");
      observer.unobserve(entry.target);
    }
  });
});

if (target) {
  observer.observe(target);
}

ตารางเปรียบเทียบ Browser APIs

API ต้องขอสิทธิ์ ใช้ทำอะไร
Geolocation ใช่ อ่านตำแหน่งผู้ใช้
Notification ใช่ แสดงแจ้งเตือน
Clipboard บางกรณี คัดลอก/อ่าน clipboard
matchMedia ไม่ ตรวจ media query
IntersectionObserver ไม่ ตรวจ element เข้า viewport

สมการระยะทางอย่างง่าย

d = (x2-x1)2 + (y2-y1)2

โดยที่ d คือระยะห่างโดยประมาณ, x₁,y₁ คือตำแหน่งจุดแรก, และ x₂,y₂ คือตำแหน่งจุดที่สอง

แบบทดสอบหลังเรียน

  1. Geolocation API ต้องขอสิทธิ์ผู้ใช้เพราะอะไร
  2. Notification API ใช้ทำอะไร
  3. Clipboard API เหมาะกับฟีเจอร์แบบใด
  4. matchMedia() ช่วยเรื่อง responsive/theme อย่างไร
  5. IntersectionObserver เหมาะกับงาน lazy loading อย่างไร

กลับสัปดาห์ที่ 5