Skip to content

Feature Detection

This lesson explains Feature Detection with clear examples, use cases, and best practices so you can use HTML5 APIs confidently in real web applications.

HTML5 API Feature Detection Overview

Feature detection is the practice of checking whether a browser supports a specific HTML5 API, method, object, event, or property before using it. Instead of guessing based on browser name or version, developers test for the actual feature and provide a fallback when support is unavailable.

Modern web applications use feature detection for APIs such as Geolocation, Clipboard, Service Workers, Web Workers, Notifications, File API, Drag and Drop, Canvas, WebGL, WebGPU, Device Orientation, and File System Access. This approach improves browser compatibility, reliability, accessibility, and user experience.

Feature Detection Topic Description
Main Goal Check support before using browser APIs.
Recommended Approach Detect features, not browser names.
Common Syntax "apiName" in object
Fallback Strategy Provide alternate behavior when unsupported.
Best For Progressive enhancement and cross-browser support.
Common APIs Clipboard, Geolocation, Workers, Canvas, Storage, Notifications.

Basic Feature Detection Example

// HTML5 API Feature Detection

if ("geolocation" in navigator) {
  navigator.geolocation.getCurrentPosition(
    (position) => {
      console.log(position.coords.latitude);
      console.log(position.coords.longitude);
    }
  );
} else {
  console.log("Geolocation is not supported.");
}

if ("clipboard" in navigator) {
  navigator.clipboard.writeText("Copied text");
} else {
  console.log("Clipboard API is not supported.");
}

This example checks whether the browser supports Geolocation and Clipboard before using them. If a feature is not available, the application can show a message, hide a button, or provide another option.

Why Feature Detection Matters

Browser support changes over time. Some APIs are widely supported, while others are experimental, permission-based, limited to HTTPS, or available only in certain browsers.

Reason Benefit Example
Browser Compatibility Prevents runtime errors in unsupported browsers. Check navigator.serviceWorker.
Progressive Enhancement Add advanced features only when supported. Enable offline support only when Service Workers exist.
Better User Experience Show helpful fallback messages. Display manual upload if File System Access is unavailable.
Security Awareness Detect secure-context-only APIs before calling them. Clipboard and MediaDevices APIs.
Cleaner Code Avoid unreliable browser sniffing. Use "fetch" in window instead of user agent checks.

Common HTML5 API Feature Checks

API Feature Detection Fallback Idea
Fetch API "fetch" in window Use XMLHttpRequest or show unsupported message.
Local Storage "localStorage" in window Use cookies or memory state.
Session Storage "sessionStorage" in window Use in-memory state.
IndexedDB "indexedDB" in window Use server storage or simpler cache.
Canvas !!document.createElement("canvas").getContext Use static image or SVG fallback.
WebGL canvas.getContext("webgl") Use Canvas 2D or static fallback.
Web Workers "Worker" in window Run small task on main thread with loading message.
Service Workers "serviceWorker" in navigator Provide online-only experience.
Geolocation "geolocation" in navigator Ask user to enter location manually.
Clipboard "clipboard" in navigator Select text manually or use legacy fallback.
Notifications "Notification" in window Use in-app alerts.
MediaDevices "mediaDevices" in navigator Use file upload instead of camera capture.
File API "File" in window && "FileReader" in window Upload directly to server without preview.
Drag and Drop "draggable" in document.createElement("span") Use file input or move buttons.
Broadcast Channel "BroadcastChannel" in window Use storage events or polling.
Device Orientation "DeviceOrientationEvent" in window Use touch, mouse, or keyboard controls.
File System Access "showOpenFilePicker" in window Use standard file input and Blob downloads.
WebGPU "gpu" in navigator Use WebGL or Canvas fallback.

Secure Context Detection

Many modern APIs require HTTPS or localhost. Use window.isSecureContext to check whether the current page is running in a secure context.

// Secure context check

if (window.isSecureContext) {
  console.log("Secure context available.");
} else {
  console.log("Use HTTPS for advanced browser APIs.");
}

if (
  window.isSecureContext &&
  "clipboard" in navigator
) {
  navigator.clipboard.writeText("Hello");
}

Permission-Aware Feature Detection

Some APIs exist in the browser but still require user permission before they can be used. Always handle permission states and user denial gracefully.

// Permission-aware feature detection

async function checkNotificationPermission() {
  if (!("Notification" in window)) {
    return "unsupported";
  }

  if (Notification.permission === "granted") {
    return "granted";
  }

  if (Notification.permission === "denied") {
    return "denied";
  }

  return "prompt";
}

checkNotificationPermission()
  .then((status) => {
    console.log("Notification status:", status);
  });

Canvas and WebGL Feature Detection

// Canvas and WebGL support check

function supportsCanvas() {
  const canvas =
    document.createElement("canvas");

  return !!(
    canvas.getContext &&
    canvas.getContext("2d")
  );
}

function supportsWebGL() {
  const canvas =
    document.createElement("canvas");

  return !!(
    canvas.getContext("webgl") ||
    canvas.getContext("experimental-webgl")
  );
}

console.log("Canvas:", supportsCanvas());
console.log("WebGL:", supportsWebGL());

Canvas and WebGL are graphics-related APIs. Use feature detection before loading heavy drawing libraries, WebGL games, or GPU-based visualizations.

Worker Feature Detection Example

// Web Worker support check

if ("Worker" in window) {
  const worker = new Worker("/worker.js");

  worker.postMessage(
    {
      type: "START"
    }
  );

  worker.addEventListener("message", (event) => {
    console.log(event.data);
  });
} else {
  console.log("Use main-thread fallback.");
}

Web Workers are useful for CPU-heavy tasks. If unsupported, keep the application functional with a simpler fallback or smaller workload.

Progressive Enhancement Fallback Pattern

// Progressive enhancement pattern

function copyText(text) {
  if (
    window.isSecureContext &&
    "clipboard" in navigator
  ) {
    return navigator.clipboard.writeText(text);
  }

  const input =
    document.createElement("input");

  input.value = text;
  document.body.appendChild(input);
  input.select();

  document.execCommand("copy");
  input.remove();

  return Promise.resolve();
}

copyText("Copied with fallback")
  .then(() => {
    console.log("Copied");
  });

This pattern uses the modern Clipboard API when available and falls back to an older copy technique when necessary. Use fallbacks carefully and avoid deprecated APIs in new code unless supporting older browsers is required.

Feature Detection Best Practices

  • Detect specific APIs, methods, properties, or events before using them.
  • Avoid browser sniffing based on user-agent strings.
  • Use progressive enhancement for advanced HTML5 APIs.
  • Provide fallback UI when features are unavailable.
  • Check secure context requirements for APIs that need HTTPS.
  • Handle permissions, errors, and rejected Promises gracefully.
  • Test feature detection on desktop and mobile browsers.
  • Keep fallback behavior accessible and user-friendly.

Common Feature Detection Mistakes

  • Checking browser names instead of checking actual API support.
  • Assuming an API works just because the object exists.
  • Ignoring HTTPS requirements for secure browser APIs.
  • Not handling permission denial or rejected Promises.
  • Failing to provide fallback behavior.
  • Using experimental APIs for critical application features.
  • Testing only in Chrome and ignoring Safari, Firefox, and mobile browsers.
  • Showing broken UI when a feature is unavailable.

Key Takeaways

  • Feature detection checks whether an API is available before using it.
  • Use "feature" in object for many browser API checks.
  • Prefer feature detection over browser detection.
  • Use progressive enhancement for advanced browser capabilities.
  • Check HTTPS and permission requirements for protected APIs.
  • Always provide accessible and reliable fallback behavior.

Pro Tip

Build the core experience first, then enhance it with HTML5 APIs only when feature detection confirms support. This keeps your website usable across browsers while still allowing modern browsers to deliver advanced experiences.