More Web APIs
A Web API is a feature the browser provides to JavaScript beyond the language itself. You have already used several: the DOM, fetch, timers, storage. This lesson tours more of them in two groups. Device APIs (location, clipboard, notifications, sharing) reach outside the page, so they require a secure page (HTTPS), often a user action, and the user's permission. Observer APIs (IntersectionObserver, ResizeObserver, MutationObserver) watch the page efficiently, replacing slow polling and scroll handlers.
In One Minute
- Feature-detect before use:
if ("geolocation" in navigator). - Powerful APIs need a secure context (HTTPS or
localhost), and many need a user gesture such as a click. - Ask for permission only when the user does something that needs it; handle "denied" gracefully.
IntersectionObserverreports when elements enter or leave view (lazy loading, infinite lists, analytics).ResizeObserverreports element size changes;MutationObserverreports DOM changes.
Permissions and Secure Contexts
| Rule | Why |
|---|---|
Secure context: HTTPS (or localhost for development) | Prevents attackers on the network from injecting code that uses your users' devices |
| User activation: a click, tap or key press first | Stops pages from popping up requests or copying data as soon as they load |
| Permission prompt | The user decides, per site |
| Permissions Policy | Sites can block features inside iframes they embed |
<script>
console.log("secure context:", window.isSecureContext);
console.log("geolocation" in navigator, "clipboard" in navigator, "Notification" in window, "share" in navigator);
navigator.permissions.query({ name: "geolocation" }).then((status) => {
console.log("geolocation state is valid:", ["granted", "denied", "prompt"].includes(status.state));
status.addEventListener("change", () => console.log("changed to", status.state));
});
</script>secure context: true
true true true false
geolocation state is valid: trueExplanation: the page is served over HTTPS, so it is a secure context. navigator.permissions.query reports a permission's state without asking: "granted", "denied" or "prompt" (the user hasn't decided yet, which is what a fresh visitor sees; the checker's automated browser has its own settings, so the example only checks for a valid value). Web Share isn't available in this desktop browser, which is exactly why you feature-detect.
Geolocation
navigator.geolocation.getCurrentPosition(success, error, options) asks for the device's location:
document.querySelector("#near-me").addEventListener("click", () => {
if (!("geolocation" in navigator)) return showMessage("Location isn't available.");
navigator.geolocation.getCurrentPosition(
(position) => {
const { latitude, longitude, accuracy } = position.coords;
showNearestOffice(latitude, longitude, accuracy);
},
(error) => {
// error.code: 1 = permission denied, 2 = position unavailable, 3 = timeout
showMessage(error.code === 1 ? "Enter your ZIP code instead." : "Couldn't find your location.");
},
{ enableHighAccuracy: false, timeout: 10_000, maximumAge: 600_000 }
);
});watchPosition reports continuous updates (return its ID to clearWatch). Location is sensitive personal data: request it only for a feature that needs it, offer an alternative (a ZIP code field), and don't store or send it further than necessary. The example needs a real permission decision, so it's shown without output.
Clipboard
The asynchronous Clipboard API reads and writes the system clipboard. Writing text usually works from a click handler; reading requires permission because the clipboard may contain anything:
<p>Receipt number: <span id="receipt">R-00042</span></p>
<button id="copy">Copy</button>
<script>
document.querySelector("#copy").addEventListener("click", async () => {
try {
await navigator.clipboard.writeText(document.querySelector("#receipt").textContent);
console.log("Copied");
} catch (err) {
console.log("Copy failed:", err.name);
}
});
</script>CopiedAlways handle failure: the user may have blocked clipboard access, or the page may be inside an iframe that isn't allowed to use it. navigator.clipboard.readText() reads, and write/read handle images and other formats.
Notifications
The Notifications API shows system notifications. Permission must be requested from a user action, and many people deny it, so treat notifications as an optional extra:
<script>
console.log("known state:", ["default", "granted", "denied"].includes(Notification.permission));
async function enableReminders() {
if (Notification.permission === "default") {
const result = await Notification.requestPermission();
if (result !== "granted") return false;
}
if (Notification.permission !== "granted") return false;
new Notification("Fee Tracker", { body: "Srihitha's payment is due tomorrow." });
return true;
}
console.log(typeof enableReminders);
</script>known state: true
functionNotification.permission is one of three strings: "default" (the user hasn't been asked yet), "granted" or "denied". (The checker's headless browser reports "denied", which is why the example prints only whether the value is one of the three.) Call enableReminders() from a button such as "Remind me", never on page load. Notifications that arrive when the page is closed need a Service Worker and the Push API.
Web Share
On phones (and some desktops), navigator.share(data) opens the system share sheet:
shareButton.addEventListener("click", async () => {
const data = { title: "Fee receipt", text: "Receipt R-00042 for $120", url: location.href };
if (navigator.canShare?.(data)) {
await navigator.share(data);
} else {
await navigator.clipboard.writeText(data.url); // fallback where sharing isn't available
}
});Observers
The observer APIs watch something and call your function when it changes. They replace patterns like checking positions in a scroll handler, which runs constantly and forces layout calculations.
IntersectionObserver
IntersectionObserver reports when elements enter or leave the viewport (or another container):
<div style="height: 2000px">Top of page</div>
<div id="footer">More payments load here</div>
<script>
const footer = document.querySelector("#footer");
const observer = new IntersectionObserver((entries) => {
for (const entry of entries) {
console.log(`${entry.target.id} visible: ${entry.isIntersecting}`);
if (entry.isIntersecting) {
console.log("Loading the next page of payments...");
observer.unobserve(entry.target);
}
}
}, { rootMargin: "200px" });
observer.observe(footer);
setTimeout(() => window.scrollTo(0, document.body.scrollHeight), 50);
</script>footer visible: false
footer visible: true
Loading the next page of payments...| Use | How |
|---|---|
| Infinite scrolling | Observe a sentinel element at the end of the list; load more when it intersects |
| Lazy-loading images | Set src when the image approaches the viewport (or use loading="lazy" in HTML) |
| "Seen" analytics | Record when a section was actually visible |
| Pausing videos | Pause when scrolled out of view |
rootMargin: "200px" triggers 200 pixels before the element is visible, so content loads before the user gets there. threshold controls how much of the element must be visible (0 to 1).
ResizeObserver and MutationObserver
<div id="panel" style="width: 300px">Fee summary</div>
<ul id="list"></ul>
<script>
const resize = new ResizeObserver((entries) => {
for (const e of entries) console.log("panel width:", Math.round(e.contentRect.width));
});
resize.observe(document.querySelector("#panel"));
setTimeout(() => { document.querySelector("#panel").style.width = "500px"; }, 50);
const mutations = new MutationObserver((records) => {
for (const r of records) console.log("children added:", r.addedNodes.length);
});
mutations.observe(document.querySelector("#list"), { childList: true });
document.querySelector("#list").append(document.createElement("li"), document.createElement("li"));
</script>children added: 2
panel width: 300
panel width: 500ResizeObserver reports an element's size when observation starts and whenever it changes, which is useful for components that adapt to their own width rather than the window's (CSS container queries now cover many such cases). MutationObserver reports DOM changes, batched: the two appended items arrived in one record.
Privacy Checklist
| Question | Good practice |
|---|---|
| Do I need this data? | Ask only for features that clearly need it |
| When do I ask? | After the user acts, with an explanation in your page |
| What if they say no? | Offer an alternative (type a ZIP code, copy a link) |
| Where does the data go? | Keep it on the device when possible; send the minimum to servers |
| Is it remembered? | Don't store location or clipboard contents unless the user expects it |
In Practice
The Fee Tracker's long payment list loads in pages as the reader scrolls, using an IntersectionObserver on a sentinel element instead of a scroll handler:
<ul id="payments" style="margin:0"></ul>
<div id="sentinel">Loading...</div>
<script>
const list = document.querySelector("#payments");
const sentinel = document.querySelector("#sentinel");
let page = 0;
function loadPage() {
page++;
for (let i = 1; i <= 50; i++) {
const li = document.createElement("li");
li.textContent = `Payment ${(page - 1) * 50 + i}`;
list.append(li);
}
console.log(`page ${page} loaded, ${list.children.length} rows`);
if (page === 2) {
observer.disconnect();
sentinel.textContent = "All payments loaded";
}
}
const observer = new IntersectionObserver((entries) => {
if (entries[0].isIntersecting) loadPage();
});
observer.observe(sentinel);
setTimeout(() => sentinel.scrollIntoView(), 100);
</script>page 1 loaded, 50 rows
page 2 loaded, 100 rowsCommon Mistakes
Using device APIs without feature detection. They may not exist. Check first.
Asking for permissions on page load. Users deny, and browsers may block future prompts. Ask from a user action.
Not handling denial or failure. Wrap calls in try...catch or provide error callbacks, and offer alternatives.
Scroll handlers for visibility. Use IntersectionObserver; it's faster and simpler.
Practice
Challenge: Use an IntersectionObserver to log "seen: totals" the first time the #totals section becomes visible, then stop observing it.
Show solution
<div style="height: 1500px"></div>
<section id="totals">Totals</section>
<script>
const io = new IntersectionObserver((entries, obs) => {
for (const entry of entries) {
if (!entry.isIntersecting) continue;
console.log("seen:", entry.target.id);
obs.unobserve(entry.target);
}
});
io.observe(document.querySelector("#totals"));
setTimeout(() => document.querySelector("#totals").scrollIntoView(), 50);
</script>seen: totalsKey Takeaways
| Need | API |
|---|---|
| Is a feature there? | "geolocation" in navigator |
| Permission state | navigator.permissions.query({ name }) |
| Copy text | await navigator.clipboard.writeText(text) |
| Element came into view | new IntersectionObserver(cb).observe(el) |
| Element resized | new ResizeObserver(cb).observe(el) |
| DOM changed | new MutationObserver(cb).observe(el, { childList: true }) |
Was this tutorial helpful?