Web APIs — Geolocation, Notifications, Workers

Browser ভর্তি free শক্তিশালী API

~35 min Intermediate 8 practice problems Live runner

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);
User-এর location পেতে browser permission চায়। প্রথম call অবশ্যই user-এর click/tap-এর মধ্যে হতে হবে।

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"));
Permission etiquette Don't ask on page load — users will deny instantly. Ask in response to a clear user action ("Notify me when bid wins").

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

worker-sim.js
// 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 (শব্দকোষ)

TermMeaningবাংলায়
Geolocation APIBrowser API to read user latitude/longitude.User-এর latitude/longitude পাওয়ার API।
getCurrentPositionReads location once, after permission.Permission পেলে এক বার location দেয়।
watchPositionStreams location updates as the user moves.User চললে continuously location update।
Notifications APIShow OS-level notifications from the page.Page থেকে OS-level notification দেখানো।
User gestureA click/tap that gates sensitive permission prompts.Permission prompt-এর জন্য জরুরি click/tap।
Web WorkerBackground JS thread; no DOM access, communicates via postMessage.Background JS thread; DOM-এ access নেই।
postMessageSend a message to / receive in a Worker.Worker-এর সাথে message বিনিময়।
Service WorkerSpecial background script for offline cache, push, and routing.Offline cache, push, route — special background script।
PWAProgressive Web App — installable, offline-capable web app.Installable, offline-capable web app।
মনে রাখুন: Browser-এ অনেক free API আছে, কিন্তু সব permission-গ্রস্ত — Geolocation, Notification, Microphone, Camera সবই user-gesture-এর ভেতরে ask করতে হয়। Heavy CPU কাজ Worker-এ পাঠান যাতে UI freeze না হয়। Service Worker দিয়ে offline-friendly PWA সম্ভব।

8. Practice Problems

  1. Write a sandbox-safe distance calculator (Haversine).
    ✨ Show Answer
    a1.js
    const 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");
  2. 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)
        );
    });
  3. 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 });
    }
  4. 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 no document/window; they message back to the main thread, which owns the DOM exclusively.

  5. Show a runnable "fake worker" that returns squared numbers via Promise.
    ✨ Show Answer
    a5.js
    const work = nums => new Promise(r =>
        setTimeout(() => r(nums.map(n => n * n)), 10));
    work([2, 3, 4]).then(console.log);
  6. 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.

  7. 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.

  8. 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.

Browser-এ অনেক free API আছে। Permission চাওয়ার সময় user gesture-এর ভেতর — এবং কারণ ব্যাখ্যা করুন। Heavy কাজ Worker-এ পাঠান।

Next Module → Capstone DOM Project — পুরো একটি app build।