JavaScript Browser APIs: Clipboard, Geolocation and Observers
Browsers give JavaScript far more than the DOM. Web APIs let a page copy to the clipboard, ask for the user’s location, notice when an element scrolls into view, watch for DOM changes, react to dark mode and detect when the tab is hidden. These features are behind “Copy” buttons, store finders, lazy-loaded images, infinite scroll and live notifications, and each one needs special handling in tests: permissions must be granted, locations mocked and scrolling simulated. In this lesson you will use the Clipboard, Geolocation and Permissions APIs, IntersectionObserver, MutationObserver, matchMedia and the Page Visibility API. The examples ran in Chrome with the permissions and a fake location provided by the test browser, exactly as Playwright does it.
📖 What You’ll Learn: what Web APIs are, secure contexts, the Permissions API, copying and reading text with the Clipboard API, getting a position with the Geolocation API and handling errors, IntersectionObserver for lazy loading, infinite scroll and visibility tracking, MutationObserver for watching DOM changes, matchMedia for dark mode and responsive breakpoints, the Page Visibility API, feature detection, and how to test these features with mocked permissions and locations.
🧰 Web APIs, Secure Contexts and Permissions
Definition: a Web API is a browser-provided interface that JavaScript can call, such as navigator.clipboard, navigator.geolocation or IntersectionObserver. They are not part of the JavaScript language and do not exist in Node.js.
- Secure context: powerful APIs (clipboard, geolocation, camera, service workers) only work on
https://pages orhttp://localhost. - Permission: sensitive APIs ask the user first. The answer is remembered per site and can be
granted,deniedorprompt(not asked yet). - Feature detection: check that an API exists before using it, since older or restricted browsers may lack it.
📄 index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Demo</title>
</head>
<body>
<script type="module" src="app.js"></script>
</body>
</html>
📄 app.js
console.log("secure context:", window.isSecureContext);
console.log("clipboard API:", "clipboard" in navigator);
console.log("geolocation API:", "geolocation" in navigator);
console.log("IntersectionObserver:", typeof IntersectionObserver);
for (const name of ["geolocation", "notifications"]) {
const status = await navigator.permissions.query({ name });
console.log(`${name} permission: ${status.state}`);
}
🖥️ Browser console (geolocation granted by the test browser)
secure context: true
clipboard API: true
geolocation API: true
IntersectionObserver: function
geolocation permission: granted
notifications permission: denied
📋 Clipboard API
navigator.clipboard.writeText() copies text and readText() reads it; both return promises. Writing is normally allowed in response to a user action such as a click; reading requires permission because the clipboard may hold private data:
📄 index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Demo</title>
</head>
<body>
<code id="coupon">SQA-WELCOME-10</code>
<button id="copy">Copy code</button>
<span id="msg"></span>
<script src="app.js"></script>
</body>
</html>
📄 app.js
const copyBtn = document.querySelector("#copy");
copyBtn.addEventListener("click", async () => {
const code = document.querySelector("#coupon").textContent;
try {
await navigator.clipboard.writeText(code);
document.querySelector("#msg").textContent = "Copied!";
console.log("copied:", code);
} catch (error) {
console.log("copy failed:", error.name);
}
});
🖥️ Browser console (after clicking Copy, clipboard read by the test)
copied: SQA-WELCOME-10
clipboard now contains: SQA-WELCOME-10
💡 Tip: To test a “Copy” button in Playwright, grant the permissions (context.grantPermissions(["clipboard-read", "clipboard-write"])), click the button, then read the clipboard with page.evaluate(() => navigator.clipboard.readText()) and assert on the value, just as the action above does.
The copy and paste DOM events let a page react to the user’s own Ctrl+C and Ctrl+V, for example to block pasting into a “confirm email” field.
📍 Geolocation API
navigator.geolocation.getCurrentPosition(success, error, options) asks for the device position once; watchPosition keeps reporting changes. It uses callbacks, so wrap it in a promise to use await:
📄 index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Demo</title>
</head>
<body>
<script type="module" src="app.js"></script>
</body>
</html>
📄 app.js
function getPosition(options) {
return new Promise((resolve, reject) =>
navigator.geolocation.getCurrentPosition(resolve, reject, options)
);
}
try {
const { coords } = await getPosition({ enableHighAccuracy: true, timeout: 5000 });
console.log(`lat ${coords.latitude}, lng ${coords.longitude}, accuracy ${coords.accuracy} m`);
const stores = [
{ name: "Bengaluru store", lat: 12.9716, lng: 77.5946 },
{ name: "Mumbai store", lat: 19.076, lng: 72.8777 },
];
const dist = (s) => Math.hypot(s.lat - coords.latitude, s.lng - coords.longitude);
const nearest = stores.reduce((a, b) => (dist(a) <= dist(b) ? a : b));
console.log("nearest:", nearest.name);
} catch (error) {
console.log(`geolocation error ${error.code}: ${error.message}`);
}
🖥️ Browser console (location mocked to Bengaluru (Koramangala))
lat 12.9352, lng 77.6245, accuracy 20 m
nearest: Bengaluru store
When the user (or the test) has not granted permission, the error callback runs instead. Always handle it, because many users say no:
📄 index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Demo</title>
</head>
<body>
<script src="app.js"></script>
</body>
</html>
📄 app.js
navigator.geolocation.getCurrentPosition(
(pos) => console.log("got position", pos.coords.latitude),
(error) => {
const reasons = { 1: "PERMISSION_DENIED", 2: "POSITION_UNAVAILABLE", 3: "TIMEOUT" };
console.log(`error ${error.code} (${reasons[error.code]}): ${error.message}`);
console.log("fallback: ask the user to type a city or PIN code");
}
);
🖥️ Browser console (permission not granted)
error 1 (PERMISSION_DENIED): User denied Geolocation
fallback: ask the user to type a city or PIN code
📌 Note: The distance calculation above is a rough comparison that works for picking the nearest of a few nearby stores. Real store locators use the haversine formula or a maps API for distances in kilometres.
👀 IntersectionObserver: Is It on Screen?
IntersectionObserver tells you when an element enters or leaves the viewport, without listening to every scroll event. It powers lazy-loaded images, infinite scroll, “seen” analytics and animations on scroll:
📄 index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Demo</title>
<style>
.block { height: 400px; border-bottom: 1px solid #ccc; }
</style>
</head>
<body>
<section class="block" id="s1">Section 1</section>
<section class="block" id="s2">Section 2</section>
<section class="block" id="s3">Section 3</section>
<section class="block" id="s4">Section 4</section>
<script src="app.js"></script>
</body>
</html>
📄 app.js
const observer = new IntersectionObserver((entries) => {
for (const entry of entries) {
const state = entry.isIntersecting ? "entered" : "left";
console.log(`${entry.target.id} ${state} (visible ratio ${entry.intersectionRatio.toFixed(1)})`);
}
}, { threshold: [0, 0.5] });
document.querySelectorAll(".block").forEach((block) => observer.observe(block));
🖥️ Browser console (viewport 1280×720, then scrolled to section 4)
s1 entered (visible ratio 1.0)
s2 entered (visible ratio 0.8)
s3 left (visible ratio 0.0)
s4 left (visible ratio 0.0)
--- scrolling to section 4 ---
s1 left (visible ratio 0.0)
s2 left (visible ratio 0.0)
s3 entered (visible ratio 0.8)
s4 entered (visible ratio 1.0)
The callback runs once at the start for every observed element, then whenever one crosses a threshold (here 0 % and 50 % visible). Useful options:
| Option | Meaning |
|---|---|
threshold | Visible fraction(s) that trigger the callback, 0 to 1 |
rootMargin: "200px" | Grow the viewport so things load before they appear |
root | A scrollable container to use instead of the viewport |
Infinite scroll
Observe a “sentinel” element at the bottom of a list; when it becomes visible, load the next page:
📄 index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Demo</title>
<style>
#feed li { height: 300px; }
</style>
</head>
<body>
<ul id="feed"></ul>
<div id="sentinel">Loading…</div>
<script src="app.js"></script>
</body>
</html>
📄 app.js
const feed = document.querySelector("#feed");
let page = 0;
function loadPage() {
page++;
for (let i = 1; i <= 5; i++) feed.insertAdjacentHTML("beforeend", `<li>Post ${(page - 1) * 5 + i}</li>`);
console.log(`loaded page ${page}, ${feed.children.length} posts`);
if (page === 3) {
observer.disconnect();
document.querySelector("#sentinel").textContent = "No more posts";
console.log("end of feed");
}
}
const observer = new IntersectionObserver(([entry]) => {
if (entry.isIntersecting) loadPage();
}, { rootMargin: "100px" });
observer.observe(document.querySelector("#sentinel"));
🖥️ Browser console (after scrolling down several times)
loaded page 1, 5 posts
loaded page 2, 10 posts
loaded page 3, 15 posts
end of feed
⚠️ Watch out: A classic infinite-scroll bug: if one page of items is shorter than the screen, the sentinel never leaves the viewport, the observer never fires again, and loading stops. Test with few and short items as well as long lists.
💡 Tip: Content that only loads on scroll is invisible to a test that never scrolls. In Playwright, scroll with locator.scrollIntoViewIfNeeded() or page.mouse.wheel(), then wait with an assertion such as expect(items).toHaveCount(15).
🔭 MutationObserver: Watch the DOM Change
MutationObserver calls you back when elements are added or removed, or when attributes or text change. It is how a script can wait for content that a framework renders later, the same idea Playwright’s auto-waiting builds on:
📄 index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Demo</title>
</head>
<body>
<div id="toasts"></div>
<button id="save">Save</button>
<script src="app.js"></script>
</body>
</html>
📄 app.js
const toasts = document.querySelector("#toasts");
const observer = new MutationObserver((mutations) => {
for (const m of mutations) {
m.addedNodes.forEach((n) => console.log("added:", n.textContent));
m.removedNodes.forEach((n) => console.log("removed:", n.textContent));
}
});
observer.observe(toasts, { childList: true });
// the app: show a toast after saving, hide it 200 ms later
document.querySelector("#save").addEventListener("click", () => {
setTimeout(() => {
const toast = document.createElement("p");
toast.textContent = "Profile saved";
toasts.append(toast);
setTimeout(() => toast.remove(), 200);
}, 100);
});
🖥️ Browser console (after clicking Save)
added: Profile saved
removed: Profile saved
A small “wait for element” helper built on MutationObserver:
📄 index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Demo</title>
</head>
<body>
<main id="app">Loading…</main>
<script type="module" src="app.js"></script>
</body>
</html>
📄 app.js
function waitForElement(selector, timeout = 2000) {
return new Promise((resolve, reject) => {
const found = document.querySelector(selector);
if (found) return resolve(found);
const observer = new MutationObserver(() => {
const el = document.querySelector(selector);
if (el) { observer.disconnect(); clearTimeout(timer); resolve(el); }
});
observer.observe(document.body, { childList: true, subtree: true });
const timer = setTimeout(() => { observer.disconnect(); reject(new Error(`${selector} not found within ${timeout} ms`)); }, timeout);
});
}
// the "app" renders the dashboard after 300 ms
setTimeout(() => { document.querySelector("#app").innerHTML = "<h2 class=\"welcome\">Welcome, Asha</h2>"; }, 300);
const start = performance.now();
const heading = await waitForElement(".welcome");
console.log(heading.textContent, `(appeared after about ${Math.round((performance.now() - start) / 100) * 100} ms)`);
try {
await waitForElement(".does-not-exist", 500);
} catch (e) {
console.log(e.message);
}
🖥️ Browser console
Welcome, Asha (appeared after about 300 ms)
.does-not-exist not found within 500 ms
🌓 matchMedia and the Page Visibility API
matchMedia evaluates a CSS media query in JavaScript, for dark mode, screen size or reduced motion, and can notify you when the answer changes. The Page Visibility API tells you when the user switches tabs, so apps can pause videos, polling or timers:
📄 index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Demo</title>
</head>
<body>
<script type="module" src="app.js"></script>
</body>
</html>
📄 app.js
const dark = matchMedia("(prefers-color-scheme: dark)");
const mobile = matchMedia("(max-width: 768px)");
const reducedMotion = matchMedia("(prefers-reduced-motion: reduce)");
console.log("dark mode:", dark.matches);
console.log("mobile layout:", mobile.matches, `(viewport ${innerWidth}px wide)`);
console.log("reduced motion:", reducedMotion.matches);
dark.addEventListener("change", (e) => console.log("theme changed, dark =", e.matches));
console.log("tab visibility:", document.visibilityState); // "hidden" when the user switches tabs
document.addEventListener("visibilitychange", () => {
if (document.hidden) { /* pause polling, videos, timers */ }
});
🖥️ Browser console (light theme at load, then the test switches to dark)
dark mode: false
mobile layout: false (viewport 1280px wide)
reduced motion: false
tab visibility: visible
theme changed, dark = true
💡 Tip: Test dark mode and responsive layouts without changing your computer: Playwright’s page.emulateMedia({ colorScheme: "dark" }) (used above) and page.setViewportSize(), or the colorScheme and viewport options in the config, change what these queries return.
🧪 Tester Scenario: Testing Permission-Based Features
Features that use permissions have at least three paths to test: permission granted, permission denied, and the API unavailable. Here a “Find nearest store” button is tested in the denied path; the granted path was shown in the geolocation section:
📄 index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Demo</title>
</head>
<body>
<button id="find">Find nearest store</button>
<p id="result"></p>
<script src="app.js"></script>
</body>
</html>
📄 app.js
document.querySelector("#find").addEventListener("click", () => {
const result = document.querySelector("#result");
if (!("geolocation" in navigator)) {
result.textContent = "Location is not supported. Enter your PIN code.";
return;
}
result.textContent = "Locating…";
navigator.geolocation.getCurrentPosition(
() => { result.textContent = "Nearest store: Koramangala"; },
() => { result.textContent = "Location blocked. Enter your PIN code to find a store."; }
);
});
🖥️ Browser console (permission denied (not granted by the test))
result: Location blocked. Enter your PIN code to find a store.
📄 stores.spec.js (Playwright)
// Playwright: the granted path with a fake location
const context = await browser.newContext({
permissions: ["geolocation"],
geolocation: { latitude: 12.9352, longitude: 77.6245 },
});
const page = await context.newPage();
await page.goto("/stores");
await page.getByRole("button", { name: "Find nearest store" }).click();
await expect(page.getByText("Nearest store: Koramangala")).toBeVisible();
📝 Practice Questions with Answers
Try each question on your own first, then open the answer to check your work. Run the code with node practice.js.
Q1. Check whether the page is a secure context and whether the Clipboard API exists.
Show answer
📄 index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Demo</title>
</head>
<body>
<script src="app.js"></script>
</body>
</html>📄 app.js
console.log(window.isSecureContext, "clipboard" in navigator);🖥️ Browser console
true trueQ2. Copy the text “Hello QA” to the clipboard and read it back.
Show answer
📄 index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Demo</title>
</head>
<body>
<script type="module" src="app.js"></script>
</body>
</html>📄 app.js
await navigator.clipboard.writeText("Hello QA");
console.log(await navigator.clipboard.readText());🖥️ Browser console
Hello QAQ3. Print the user’s coordinates rounded to 2 decimal places, or “unknown” on error.
Show answer
📄 index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Demo</title>
</head>
<body>
<script src="app.js"></script>
</body>
</html>📄 app.js
navigator.geolocation.getCurrentPosition(
({ coords }) => console.log(coords.latitude.toFixed(2), coords.longitude.toFixed(2)),
() => console.log("unknown")
);🖥️ Browser console (location mocked to New Delhi)
28.61 77.21Q4. Log “footer seen” the first time the footer scrolls into view, then stop observing.
Show answer
📄 index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Demo</title>
<style>
main { height: 1500px; }
</style>
</head>
<body>
<main>Long page</main>
<footer id="footer">Footer</footer>
<script src="app.js"></script>
</body>
</html>📄 app.js
const footer = document.querySelector("#footer");
const observer = new IntersectionObserver(([entry]) => {
if (entry.isIntersecting) {
console.log("footer seen");
observer.disconnect();
}
});
observer.observe(footer);🖥️ Browser console (after scrolling down, up and down again)
footer seenQ5. Use MutationObserver to log whenever the class attribute of #status changes.
Show answer
📄 index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Demo</title>
</head>
<body>
<div id="status" class="pending">Order status</div>
<script src="app.js"></script>
</body>
</html>📄 app.js
const status = document.querySelector("#status");
new MutationObserver((mutations) => {
for (const m of mutations) console.log(`class: ${m.oldValue} -> ${status.className}`);
}).observe(status, { attributes: true, attributeFilter: ["class"], attributeOldValue: true });
setTimeout(() => { status.className = "shipped"; }, 50);
setTimeout(() => { status.className = "delivered"; }, 100);🖥️ Browser console
class: pending -> shipped
class: shipped -> deliveredQ6. Log “mobile” or “desktop” depending on whether the viewport is at most 768 px wide.
Show answer
📄 index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Demo</title>
</head>
<body>
<script src="app.js"></script>
</body>
</html>📄 app.js
console.log(matchMedia("(max-width: 768px)").matches ? "mobile" : "desktop", innerWidth);🖥️ Browser console (viewport 1280×720)
desktop 1280🧠 MCQ Quiz: Browser APIs
10 questions on this lesson. Pick one answer for each, then press Check answers to see your score and an explanation for every question.
- Which object gives access to the Clipboard API?Answer: navigator.clipboard. Its methods return promises.
- On which pages do APIs such as clipboard and geolocation work?Answer: Secure contexts: https or localhost. Check window.isSecureContext.
- What are the possible states of a permission?Answer: granted, denied, prompt. prompt means the user has not been asked yet.
- What does getCurrentPosition call when the user refuses?Answer: The error callback with code 1 (PERMISSION_DENIED). Always provide an error callback.
- What is IntersectionObserver used for?Answer: Detecting when elements enter or leave the viewport. Lazy loading and infinite scroll use it.
- What does the
rootMarginoption do?Answer: Expands or shrinks the area used to detect intersection. A positive margin triggers earlier. - Which API notifies you when elements are added to the DOM?Answer: MutationObserver. Use childList and subtree options.
- How do you check for dark mode in JavaScript?Answer: matchMedia(“(prefers-color-scheme: dark)”).matches. Listen to its change event for updates.
- Which property tells you whether the tab is hidden?Answer: document.visibilityState. Listen to visibilitychange.
- How does Playwright test a geolocation feature?Answer: Grant the permission and set a fake geolocation on the context. Both are browser context options.
💼 Interview Questions and Answers
Q1. How would you test a feature that uses the user’s location?
Cover the granted path with mocked coordinates for several places (including edge locations such as borders or outside the service area), the denied path (the app must offer a fallback such as a PIN code), a timeout or unavailable position, and browsers or contexts without the API. In Playwright, set permissions and geolocation on the browser context and change it with context.setGeolocation() mid-test.
Q2. What is IntersectionObserver and why is it better than a scroll listener?
It asynchronously reports when observed elements cross visibility thresholds relative to the viewport or a container. Unlike a scroll listener, it does not run on every scroll frame or force layout calculations with getBoundingClientRect, so it is far cheaper. It is used for lazy loading, infinite scroll, ad viewability and “seen” tracking.
Q3. How do automation tools wait for dynamic content, and what browser API can do something similar?
Playwright re-checks locators until they match the expected state (visible, enabled, has text) or a timeout expires, polling and reacting to DOM changes. In plain JavaScript a MutationObserver on document.body with childList and subtree can resolve a promise when a selector appears, which is essentially a hand-written waitForSelector.
Q4. What problems do permission prompts cause in automated tests?
A native permission dialog blocks the flow and cannot be clicked like page content, and its default answer differs between browsers and CI machines, causing flaky results. Grant or deny permissions explicitly in the browser context for each test, and include tests for both outcomes.
❓ Frequently Asked Questions
🤔 Why does navigator.clipboard work locally but not on my staging site?
Staging is probably served over plain http. The Clipboard API requires a secure context: https, or localhost during development.
🤔 Is the Geolocation position accurate?
It depends on the device: GPS on phones is accurate to metres, while desktops use Wi-Fi or IP lookup and can be off by kilometres. Check coords.accuracy.
🤔 What is ResizeObserver?
A sibling of the other observers that reports when an element’s size changes, useful for responsive components and charts.
🤔 Can I use these APIs in Node.js?
No. They are browser APIs. Node.js has its own modules for files, network and processes; tests use a real browser (Playwright) to exercise these features.
🏁 Summary
- Web APIs are browser features; many need a secure context (https or localhost) and user permission.
- Clipboard:
navigator.clipboard.writeText/readText; Geolocation:getCurrentPositionwith success and error callbacks. - IntersectionObserver detects visibility for lazy loading and infinite scroll; MutationObserver reacts to DOM changes.
matchMediareads media queries (dark mode, breakpoints);document.visibilityStatetracks hidden tabs.- Test granted, denied and unsupported paths by setting permissions, fake locations, scrolling and media emulation in the test browser.
Next, continue with Lesson 62: Web Page Automation Basics.
🎬 Watch JavaScript and automation tutorials on YouTube!
Subscribe to SqaToolsByDY • Practice on sqatools.in