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"]
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();
async function showNotification() {
// ขอสิทธิ์แจ้งเตือน
const permission = await Notification.requestPermission();
if (permission === "granted") {
new Notification("CAI Online", {
body: "ถึงเวลาเรียนบท DOM แล้ว",
icon: "/static/icon.png"
});
}
}
// ตัวอย่างการใช้งาน
// showNotification();
async function copyText(text) {
try {
// คัดลอกข้อความไปยัง clipboard
await navigator.clipboard.writeText(text);
console.log("คัดลอกแล้ว");
} catch (error) {
console.log("คัดลอกไม่สำเร็จ", error);
}
}
// ตัวอย่างการใช้งาน
copyText("https://example.com");
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);
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);
}
| API | ต้องขอสิทธิ์ | ใช้ทำอะไร |
|---|---|---|
| Geolocation | ใช่ | อ่านตำแหน่งผู้ใช้ |
| Notification | ใช่ | แสดงแจ้งเตือน |
| Clipboard | บางกรณี | คัดลอก/อ่าน clipboard |
| matchMedia | ไม่ | ตรวจ media query |
| IntersectionObserver | ไม่ | ตรวจ element เข้า viewport |
โดยที่ d คือระยะห่างโดยประมาณ, x₁,y₁ คือตำแหน่งจุดแรก, และ x₂,y₂ คือตำแหน่งจุดที่สอง
matchMedia() ช่วยเรื่อง responsive/theme อย่างไร