Skip to content
jshacks.dev
Browser

How to Feature-Detect Browser APIs

Feature-detect browser APIs instead of sniffing: the in operator, CSS.supports, supports methods, try and catch probes, @supports and polyfill loading.

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

A browser version number tells you very little about what a page can do. Features ship at different times in different engines, can be turned off by settings or policies, vary between desktop and mobile and are sometimes present but broken. The reliable way to decide whether to use a feature is to ask the browser directly: does this object, method, CSS property or file format exist and work? That is feature detection, and it replaced user agent sniffing years ago. Done well, it lets you use new APIs where they exist and fall back gracefully where they do not, without a list of browser names to maintain. This guide shows how to feature-detect browser APIs: the basic existence checks with in and property access, the supports() methods built into several APIs, CSS detection with CSS.supports() and @supports, probing behavior with try and catch, detecting HTML features through created elements, handling secure context and permission constraints, patterns for graceful fallback and progressive enhancement, loading polyfills only when needed and testing both paths. The references are on MDN and the compatibility tables at caniuse.

Why not check the browser

Version checks rot. A rule such as "Chrome 100 or later supports this" is wrong for Chromium-based browsers with different release schedules, for embedded web views that lag behind, for browsers that disable a feature and for those that gain it later than expected. User agent strings are also being reduced and can be spoofed. Detection of the feature itself is always accurate to the environment where the code runs, so a user in an unusual browser gets the best path available, not a guess.

Existence checks

For objects and methods, test whether the name exists. The in operator checks a property on an object, including inherited ones, and typeof checks that something is a function without throwing for an undeclared global.

exists.jsJavaScript
const features = {
  fetch: typeof fetch === "function",
  serviceWorker: "serviceWorker" in navigator,
  intersectionObserver: "IntersectionObserver" in window,
  clipboard: Boolean(navigator.clipboard?.writeText),
  structuredClone: typeof structuredClone === "function",
  resizeObserver: typeof ResizeObserver !== "undefined",
};

console.log(features);
Text
{
  fetch: true,
  serviceWorker: true,
  intersectionObserver: true,
  clipboard: true,
  structuredClone: true,
  resizeObserver: true
}

Test the exact method you will call, not only the object that holds it: navigator.clipboard can exist while readText does not, in browsers that implement part of the interface. Optional chaining keeps the check on one line, as with navigator.clipboard?.writeText. Referencing an undeclared global directly, as in if (ResizeObserver), throws a ReferenceError, which is why typeof is used for globals.

Detect new language syntax

Syntax errors cannot be caught by an if, since a script containing unsupported syntax fails to parse as a whole. Two techniques exist. Put modern syntax in a separate module or file and load it only when a probe succeeds, and probe with new Function() or eval inside try, though a Content Security Policy that forbids unsafe-eval blocks it. The simplest practical approach today is to compile for a target set of browsers with your build tool and use a module script as a gate: browsers that understand type="module" have a known baseline.

gate.htmlHTML
<script type="module" src="/app.modern.js"></script>
<script nomodule src="/app.legacy.js"></script>
Text
(browsers with module support load the modern file and skip the legacy one)

For methods that were added to the language later, such as Array.prototype.at or Object.groupBy, a runtime existence check is enough: typeof Object.groupBy === "function".

Built-in support methods

Several APIs provide a direct question for their options. HTMLScriptElement.supports() reports whether a script type, such as importmap, is understood. MediaRecorder.isTypeSupported() and HTMLMediaElement.canPlayType() report formats. Intl.DateTimeFormat.supportedLocalesOf() and Intl.supportedValuesOf() report data. CSS.supports() is covered next. PerformanceObserver.supportedEntryTypes lists the entry types.

supports.jsJavaScript
console.log(HTMLScriptElement.supports?.("importmap"));
console.log(MediaRecorder.isTypeSupported("audio/webm;codecs=opus"));
console.log(document.createElement("video").canPlayType('video/mp4; codecs="avc1.42E01E"'));
console.log(PerformanceObserver.supportedEntryTypes.includes("largest-contentful-paint"));
console.log(Intl.supportedValuesOf("timeZone").length > 0);
Text
true
true
probably
true
true

Note that canPlayType() returns an empty string, "maybe" or "probably", not a boolean, and that the answer is about the container and codec, not about whether a particular file will play. When an API offers such a method, prefer it to guessing from a name.

Detect CSS support

In JavaScript, CSS.supports() takes a property and a value, or a full condition string, and returns a boolean.

css.jsJavaScript
console.log(CSS.supports("display", "grid"));
console.log(CSS.supports("(container-type: inline-size)"));
console.log(CSS.supports("selector(:has(a))"));
console.log(CSS.supports("color", "oklch(60% 0.2 250)"));
console.log(CSS.supports("anchor-name", "--a"));

if (CSS.supports("view-transition-name", "x")) {
  document.documentElement.classList.add("has-view-transitions");
}
Text
true
true
true
true
false

Inside stylesheets, @supports does the same without script, with a fallback written outside the block and the new code inside it.

supports.cssCSS
.layout {
  display: flex;
  flex-wrap: wrap;
}

@supports (display: grid) and (gap: 1rem) {
  .layout {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(16rem, 1fr));
    gap: 1rem;
  }
}

@supports not (backdrop-filter: blur(4px)) {
  .overlay {
    background: rgb(0 0 0 / 0.8);
  }
}
Text
(grid is used where supported, flex elsewhere, and the overlay is more opaque without blur)

Unknown properties inside a normal rule are simply ignored by browsers, so for many cases you can write the old declaration first and the new one after it, and let the cascade choose; @supports is for when the new feature needs several coordinated rules.

Detect HTML features

Create an element and check for a property it should have in browsers that support the feature. This is how libraries detect support for input types, attributes and elements.

html.jsJavaScript
const input = document.createElement("input");
input.setAttribute("type", "date");
console.log("date input:", input.type === "date");

console.log("dialog:", typeof HTMLDialogElement === "function");
console.log("loading=lazy:", "loading" in HTMLImageElement.prototype);
console.log("popover:", Object.hasOwn(HTMLElement.prototype, "popover"));
console.log("inert:", "inert" in HTMLElement.prototype);
Text
date input: true
dialog: true
loading=lazy: true
popover: true
inert: true

For an input type, a browser that does not understand it falls back to text, so the type property reads back as text. Checking the prototype for attribute-backed properties is a cheap and accurate technique that needs no element at all.

Probe by behavior

Sometimes the API exists but is unusable: storage that throws in private mode, a feature disabled by a policy or an implementation that is incomplete. Test by trying it in a try block.

probe.jsJavaScript
function storageAvailable(type) {
  try {
    const storage = window[type];
    const key = "__probe__";
    storage.setItem(key, "1");
    storage.removeItem(key);
    return true;
  } catch {
    return false;
  }
}

console.log(storageAvailable("localStorage"));

function supportsPassiveListeners() {
  let supported = false;
  try {
    const options = {
      get passive() {
        supported = true;
        return false;
      },
    };
    addEventListener("test", null, options);
    removeEventListener("test", null, options);
  } catch {
    /* ignore */
  }
  return supported;
}

console.log(supportsPassiveListeners());
Text
true
true

The passive listener probe is a classic: the browser reads the passive property of the options object only if it supports it. Cache the result of a probe, since repeating it on every call is wasteful.

Secure contexts and permissions

Many modern APIs exist only in secure contexts, so window.isSecureContext is part of detection: navigator.clipboard, navigator.mediaDevices, service workers and crypto.subtle are undefined on plain HTTP pages. And an API being present does not mean you may use it: camera, location and notifications need permission, which can be queried in many browsers with the Permissions API, and denied by the user at any time. Treat "supported" and "allowed" as two checks, and handle denial as a normal outcome.

permission.jsJavaScript
async function canUseGeolocation() {
  if (!("geolocation" in navigator) || !window.isSecureContext) return false;
  try {
    const status = await navigator.permissions.query({ name: "geolocation" });
    return status.state !== "denied";
  } catch {
    return true;
  }
}
Text
(returns false when unsupported, insecure or denied)

Graceful fallbacks and progressive enhancement

Design in layers. Start with a baseline that works everywhere, using plain HTML and CSS, then add enhancements guarded by detection. A form works with a normal submit, and where fetch and FormData exist you intercept it. A list of links works, and where IntersectionObserver exists it lazy loads. The test of a good fallback is that a user without the feature can still do the task, perhaps with less polish.

enhance.jsJavaScript
if ("IntersectionObserver" in window) {
  lazyLoadImages();
} else {
  document.querySelectorAll("img[data-src]").forEach((img) => (img.src = img.dataset.src));
}
Text
(old browsers load all images immediately instead of lazily)

Avoid fallbacks that quietly lose data or fail silently; if a critical feature is missing and there is no alternative, say so in the interface.

Load polyfills only when needed

A polyfill adds a missing feature in JavaScript. Ship it only to browsers that need it, by detecting first and loading dynamically, so modern browsers do not download it.

polyfill.jsJavaScript
async function ensureStructuredClone() {
  if (typeof structuredClone === "function") return;
  const { default: clone } = await import("/vendor/structured-clone-polyfill.js");
  globalThis.structuredClone = clone;
}

await ensureStructuredClone();
console.log(structuredClone({ a: [1, 2, 3] }));
Text
{ a: [ 1, 2, 3 ] }

Check whether a polyfill exists and is reliable before you write your own, and consider whether the feature is now available in every browser you support, in which case the check and the polyfill can be deleted. Browser support data, such as the Baseline status of a feature, helps decide when to drop old fallbacks.

Test both paths

Detection code has two branches, and the unusual one rarely runs. Test the fallback by forcing the check to fail: in tests, delete or stub the API before calling your code, for example delete window.IntersectionObserver, or set a flag. Run the page in the oldest browser you support, and with features disabled in developer tools. A unit test that runs only the modern branch leaves the fallback unverified until a user finds the bug.

test.jsJavaScript
const original = window.IntersectionObserver;
delete window.IntersectionObserver;

lazyLoadImages();
console.log(document.querySelector("img").src.endsWith("photo.jpg"));

window.IntersectionObserver = original;
Text
true
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.