Skip to content
jshacks.dev
Browser

The EyeDropper and Other Small Web APIs

A tour of small web APIs worth knowing: EyeDropper, Web Share, Screen Wake Lock, Vibration, Clipboard and Badging, with feature detection and support notes.

8 min read
Summarize in AI
Flat illustration of a browser and a server trading a request and a response, with the Google Chrome, GraphQL, NGINX and Swagger logos.

Beyond the large platform features such as fetch and the DOM, the browser ships a long tail of small APIs, each solving one narrow problem with a few lines of code: pick a color from anywhere on the screen, hand a link to the system share sheet, keep the screen awake during a recipe, copy text to the clipboard, show a number on an app icon. They are easy to miss because each of them touches a corner of the platform, and easy to misuse because most are gated by permissions, user gestures, secure contexts and uneven browser support. This post covers the EyeDropper API in detail, then a tour of other small APIs that are worth knowing: Web Share, Screen Wake Lock, the Clipboard API, the Vibration API and the Badging API, with working code, the conditions each requires and how to detect support. All of them need a secure context, which means HTTPS or localhost, and most need a user gesture. Support varies, and several are limited to Chromium browsers or to mobile devices, so every example uses feature detection and treats the feature as an enhancement. The references are the MDN EyeDropper page and the pages linked in each section.

EyeDropper

The EyeDropper API lets a page open the browser's eyedropper tool, the magnifier that follows the cursor and picks the color of any pixel on the screen, including outside the browser window. It is meant for design tools, theme editors and color pickers, where the native input <input type="color"> is too limited. The API is two lines: construct an EyeDropper and call open(), which returns a promise for an object with an sRGBHex string.

eyedropper.jsJavaScript
async function pickColor() {
  if (!("EyeDropper" in window)) {
    console.log("EyeDropper not supported");
    return null;
  }

  const dropper = new EyeDropper();

  try {
    const { sRGBHex } = await dropper.open();
    console.log(sRGBHex);
    return sRGBHex;
  } catch (error) {
    console.log("canceled:", error.name);
    return null;
  }
}

document.querySelector("#pick").addEventListener("click", pickColor);
Text
#3b82f6

The result is a lowercase hex string such as #3b82f6. The call needs a user gesture, since taking over the cursor must be requested by the user, and the user can cancel with Escape, which rejects with an AbortError. You can also cancel from code by passing an AbortSignal: dropper.open({ signal }). The page never sees the pixels around the one picked, and cannot sample colors without the user choosing, which is why no permission prompt is needed. Support is in Chromium browsers; Firefox and Safari do not implement it, so offer a fallback: a normal <input type="color"> always works, and gives the same kind of value.

fallback.jsJavaScript
const input = document.querySelector("#color");
const button = document.querySelector("#pick");

if ("EyeDropper" in window) {
  button.addEventListener("click", async () => {
    try {
      const { sRGBHex } = await new EyeDropper().open();
      input.value = sRGBHex;
      input.dispatchEvent(new Event("input", { bubbles: true }));
    } catch {
      // the user pressed Escape
    }
  });
} else {
  button.hidden = true;
}
Text
(the pick button appears only where the API exists; the color input always works)

Colors from the eyedropper are in sRGB, so on a wide-gamut display it returns the closest sRGB value, which is fine for most uses. A common follow-up is to convert the hex to HSL or OKLCH for a palette, which is plain math, or to check contrast against another color for accessibility.

Web Share

navigator.share() opens the operating system's share sheet with a title, text, URL and, in some browsers, files. It makes a "Share" button feel native on phones and on desktops with a share target, such as Safari on macOS and Edge on Windows.

share.jsJavaScript
async function share() {
  const data = { title: "Back/forward cache", text: "A short guide", url: location.href };

  if (!navigator.share || (navigator.canShare && !navigator.canShare(data))) {
    await navigator.clipboard.writeText(data.url);
    console.log("link copied");
    return;
  }

  try {
    await navigator.share(data);
    console.log("shared");
  } catch (error) {
    if (error.name !== "AbortError") throw error;
  }
}

document.querySelector("#share").addEventListener("click", share);
Text
shared

It needs a user gesture and a secure context, rejects with AbortError when the user closes the sheet, and does not tell you which app was chosen, by design. navigator.canShare() checks whether the data is acceptable, which matters for files. A fallback that copies the link to the clipboard is the usual alternative on browsers without it.

Screen Wake Lock

A recipe, a presentation, a boarding pass or a navigation view should not dim the screen while the user is reading it. navigator.wakeLock.request("screen") asks the system to keep the screen on, and returns a sentinel that you release when done.

wakelock.jsJavaScript
let sentinel = null;

async function keepAwake() {
  if (!("wakeLock" in navigator)) return;

  try {
    sentinel = await navigator.wakeLock.request("screen");
    sentinel.addEventListener("release", () => console.log("wake lock released"));
    console.log("screen will stay on");
  } catch (error) {
    console.log("not granted:", error.name);
  }
}

document.addEventListener("visibilitychange", () => {
  if (document.visibilityState === "visible" && sentinel?.released) keepAwake();
});

keepAwake();
Text
screen will stay on

The browser releases the lock when the page is hidden, when the battery is low, or when the user turns it off, so re-acquire it on visibilitychange, as shown. It needs the page to be visible and a secure context, and it needs a user gesture in some browsers. Release with sentinel.release() when the reason for staying awake is over, since an unneeded wake lock drains the battery. Support is wide in current browsers.

Clipboard API

The asynchronous Clipboard API replaces document.execCommand("copy"). navigator.clipboard.writeText() copies text, and readText() reads it, with a permission prompt for reading.

clipboard.jsJavaScript
async function copy(text) {
  try {
    await navigator.clipboard.writeText(text);
    console.log("copied:", text);
  } catch (error) {
    console.log("copy failed:", error.name);
  }
}

document.querySelector("#copy").addEventListener("click", () => copy("npm install example"));
Text
copied: npm install example

Writing needs a secure context and a user gesture, or the page to be focused, and reading prompts the user. Richer content goes through navigator.clipboard.write() with ClipboardItem, for instance an image blob or HTML and plain text together, which lets one copy action paste correctly into both a rich editor and a plain one.

rich.jsJavaScript
async function copyRich(html, plain) {
  const item = new ClipboardItem({
    "text/html": new Blob([html], { type: "text/html" }),
    "text/plain": new Blob([plain], { type: "text/plain" }),
  });
  await navigator.clipboard.write([item]);
  console.log("copied rich text");
}
Text
copied rich text

Vibration

navigator.vibrate() buzzes a phone, for haptic feedback on a successful action or a timer. It takes a duration or a pattern of durations in milliseconds.

vibrate.jsJavaScript
function buzz(pattern) {
  if (!("vibrate" in navigator)) return false;
  return navigator.vibrate(pattern);
}

console.log(buzz(50));
console.log(buzz([100, 50, 100]));
Text
true
true

It works on Android Chromium and Firefox, and is not available in Safari on iOS. Browsers require a user interaction first, and it does nothing on devices without a vibration motor, so never use it as the only signal for something important. Use it sparingly, since repeated vibration annoys users, and respect prefers-reduced-motion as a hint for sensory comfort.

Badging

navigator.setAppBadge(count) shows a number or a dot on an installed web app's icon, such as unread messages, and clearAppBadge() removes it. It works for installed progressive web apps on desktop and Android in Chromium browsers.

badge.jsJavaScript
async function updateBadge(unread) {
  if (!("setAppBadge" in navigator)) return;

  if (unread > 0) {
    await navigator.setAppBadge(unread);
  } else {
    await navigator.clearAppBadge();
  }
  console.log("badge:", unread);
}

updateBadge(3);
Text
badge: 3

It needs no permission for installed apps, and can be called from a service worker too, which is how a push notification can update the badge when the page is closed.

Other APIs in the same spirit

A few more are worth a mention. The Barcode Detection API reads barcodes and QR codes from images and the camera in Chromium browsers on supported platforms. The Contact Picker API lets the user choose contacts to share with a page on Android. The File System Access API opens, edits and saves local files with showOpenFilePicker() in Chromium browsers. The Idle Detection API reports when the user is idle, behind a permission, and the Network Information API gives a rough connection type in Chromium. The Web Locks API coordinates work across tabs, and has wide support. Each follows the same pattern: check support, call from a gesture and handle the rejection.

A feature detection habit

All of these APIs share the same shape of use, and a small pattern keeps the code tidy: ask whether the feature exists, offer the control only if it does and make the fallback behavior the default.

enhance.jsJavaScript
const features = {
  eyedropper: "EyeDropper" in window,
  share: typeof navigator.share === "function",
  wakeLock: "wakeLock" in navigator,
  clipboard: Boolean(navigator.clipboard?.writeText),
  vibrate: "vibrate" in navigator,
  badge: "setAppBadge" in navigator,
};

for (const [name, supported] of Object.entries(features)) {
  document.querySelectorAll(`[data-feature="${name}"]`).forEach((el) => {
    el.hidden = !supported;
  });
}

console.log(Object.values(features).filter(Boolean).length);
Text
5

Elements marked with data-feature="share" and the like are hidden when the feature is missing. The number depends on the browser. This keeps the markup honest: users never see a button that cannot work.

Privacy and permissions

Small does not mean harmless. Reading the clipboard, keeping the screen awake and reading contacts all touch something the user cares about, so browsers gate them behind gestures and prompts, and users can turn them off. Ask only when the user has just done something that explains the request, say what you will do with it, and handle denial without a dead end. Do not use any of them for fingerprinting, and do not call them from third-party scripts you do not control without thinking about what they can reach.

Testing

Feature detection makes testing straightforward: in a test, define a stub for the API, such as a fake navigator.share that records its argument, and assert on the call and on the fallback when it is absent. For the real behavior, test in the browsers that support it, on a device where relevant: wake lock and vibration need a phone, and the eyedropper needs a desktop Chromium browser.

test.jsJavaScript
const calls = [];
Object.defineProperty(navigator, "share", {
  value: async (data) => calls.push(data),
  configurable: true,
});

await navigator.share({ title: "Test", url: "https://example.com" });
console.log(calls.length, calls[0].title);
Text
1 Test
Also inAPIs
Share

Keep reading

Flat illustration of a browser and a server trading a request and a response, with the Google Chrome, Swagger, Postman and NGINX logos.
Browser

The DOM Tree: Nodes, Elements and Text

Understand the DOM tree: node types, the difference between nodes and elements, text and comment nodes, tree navigation properties and how whitespace shows up.

6 min read
Flat illustration of an editor window full of code, with the Google Chrome, JavaScript and npm logos.
Browser

script Tags: async, defer and type=module

Compare classic, async, defer and module script tags: when each downloads, when each runs, how order is kept and which one to pick for each kind of script.

6 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.