Web APIs — Geolocation, Notifications, Workers
Browser ভর্তি free শক্তিশালী API
1. Geolocation
// Always inside a user gesture (click) — browsers require it
btn.addEventListener("click", () => {
navigator.geolocation.getCurrentPosition(
pos => {
console.log(pos.coords.latitude, pos.coords.longitude);
console.log("accuracy ±", pos.coords.accuracy, "m");
},
err => console.error(err.message),
{ enableHighAccuracy: true, timeout: 10_000, maximumAge: 60_000 }
);
});
// Continuous updates
const id = navigator.geolocation.watchPosition(p => { /* ... */ });
// navigator.geolocation.clearWatch(id);
2. Notifications
async function notify(title, body) {
if (Notification.permission === "denied") return;
if (Notification.permission !== "granted") {
const r = await Notification.requestPermission();
if (r !== "granted") return;
}
new Notification(title, { body, icon: "/favicon.png" });
}
btn.addEventListener("click", () => notify("Order shipped", "ETA 2 days"));
3. Web Workers
A Worker runs JavaScript on a separate thread. The main thread stays responsive while heavy work happens elsewhere. Communication happens through postMessage + onmessage.
// main.js
const w = new Worker("worker.js");
w.postMessage({ start: 1, end: 1_000_000 });
w.onmessage = (e) => console.log("sum =", e.data);
// worker.js
onmessage = (e) => {
const { start, end } = e.data;
let sum = 0;
for (let i = start; i <= end; i++) sum += i;
postMessage(sum);
};
Workers cannot touch the DOM, but they have fetch, timers, IndexedDB, and most non-UI APIs.
4. Sandbox-Safe Worker Simulation
// Simulate "send work to a worker, get answer back"
function runOnWorker(message) {
return new Promise(resolve => {
setTimeout(() => { // pretend the worker is busy
let sum = 0;
for (let i = message.start; i <= message.end; i++) sum += i;
resolve(sum);
}, 10);
});
}
(async () => {
const result = await runOnWorker({ start: 1, end: 1000 });
console.log("sum 1..1000 =", result);
})();
5. Service Workers — Preview
A Service Worker is a special background script that intercepts network requests, enables offline pages, and powers Push notifications. Unlocking PWA-grade behaviour. Coming with the framework lectures.
// main.js
if ("serviceWorker" in navigator) {
navigator.serviceWorker.register("/sw.js");
}
// sw.js
self.addEventListener("fetch", (event) => {
event.respondWith(
caches.match(event.request).then(r => r || fetch(event.request))
);
});
6. Permission Patterns
- Always ask in response to a user gesture, not at page load
- Explain why you need it before triggering the prompt
- Provide a fallback if permission is denied
- Cache the user's choice — don't re-prompt repeatedly
7. Glossary (শব্দকোষ)
| Term | Meaning | বাংলায় |
|---|---|---|
| Geolocation API | Browser API to read user latitude/longitude. | User-এর latitude/longitude পাওয়ার API। |
getCurrentPosition | Reads location once, after permission. | Permission পেলে এক বার location দেয়। |
watchPosition | Streams location updates as the user moves. | User চললে continuously location update। |
| Notifications API | Show OS-level notifications from the page. | Page থেকে OS-level notification দেখানো। |
| User gesture | A click/tap that gates sensitive permission prompts. | Permission prompt-এর জন্য জরুরি click/tap। |
| Web Worker | Background JS thread; no DOM access, communicates via postMessage. | Background JS thread; DOM-এ access নেই। |
postMessage | Send a message to / receive in a Worker. | Worker-এর সাথে message বিনিময়। |
| Service Worker | Special background script for offline cache, push, and routing. | Offline cache, push, route — special background script। |
| PWA | Progressive Web App — installable, offline-capable web app. | Installable, offline-capable web app। |
8. Practice Problems
- Write a sandbox-safe distance calculator (Haversine).
✨ Show Answer
a1.jsconst hav = (a, b) => Math.sin((b - a) / 2) ** 2; function dist(la1, lo1, la2, lo2) { const R = 6371; // km const rad = d => d * Math.PI / 180; const [a1, a2, lo] = [rad(la1), rad(la2), rad(lo2 - lo1)]; const a = hav(a1, a2) + Math.cos(a1) * Math.cos(a2) * hav(0, lo); return R * 2 * Math.asin(Math.sqrt(a)); } // Dhaka → Chittagong console.log(dist(23.81, 90.41, 22.36, 91.78).toFixed(1), "km"); - Sketch a click handler that fetches the user's location.
✨ Show Answer
btn.addEventListener("click", () => { navigator.geolocation.getCurrentPosition( p => show(p.coords), e => alert(e.message) ); }); - Write a notify() that uses requestPermission lazily.
✨ Show Answer
async function notify(t, body) { let p = Notification.permission; if (p === "default") p = await Notification.requestPermission(); if (p === "granted") new Notification(t, { body }); } - Why can't a Worker touch the DOM?
✨ Show Answer
Answer: The DOM is not thread-safe — letting two threads mutate the same tree would create races. Workers run in a parallel JS environment with their own globals (
self) and nodocument/window; they message back to the main thread, which owns the DOM exclusively. - Show a runnable "fake worker" that returns squared numbers via Promise.
✨ Show Answer
a5.jsconst work = nums => new Promise(r => setTimeout(() => r(nums.map(n => n * n)), 10)); work([2, 3, 4]).then(console.log); - List 3 use-cases for a Service Worker.
✨ Show Answer
(1) Offline cache (app shell + last data). (2) Background sync — queue requests while offline, replay when back. (3) Push notifications from server while the page is closed.
- Why is a user gesture required for sensitive permissions?
✨ Show Answer
Answer: To prevent silent abuse — without the gesture rule, a malicious page could open a permission prompt on every visit until the user clicks "allow" by accident. Tying it to a click ensures the user is intentionally interacting with that feature.
- Sketch a watchPosition that updates a map div every move.
✨ Show Answer
const id = navigator.geolocation.watchPosition( p => map.setCenter(p.coords), e => console.error(e.message), { enableHighAccuracy: true } ); // later: navigator.geolocation.clearWatch(id);
Summary — Module 29
Browsers ship a deep stack of free APIs — Geolocation, Notifications, Workers (CPU-heavy off-thread), Service Workers (offline + push). Always ask permission inside a user gesture, explain why, and degrade gracefully on denial.