JS Navigator
JavaScript navigator: Checking Capabilities and Web APIs
The JavaScript window.navigator object exposes information about the browser environment and hardware capabilities, including network status, preferred language, clipboard access, and geolocation. Always test specific API support directly rather than guessing from navigator.userAgent.
Useful navigator Properties and APIs
navigator.onLine: Returnstrueorfalsebased on basic network connectivity (pair with"online"and"offline"window events).navigator.language/navigator.languages: Reports the user's preferred UI locale, such as"en-US".navigator.clipboard: Async Clipboard API (writeText(),readText()) for copy buttons over HTTPS.navigator.hardwareConcurrency: Approximate number of logical CPU cores available for sizing Web Worker pools.
Feature Detection vs. userAgent Sniffing
Never write if (navigator.userAgent.includes("Chrome")) to decide whether a feature works, because browsers regularly change user-agent strings or freeze them for privacy. Check the capability itself instead.
console.log("Online status:", navigator.onLine);
console.log("Preferred language:", navigator.language);
console.log("Logical CPU cores:", navigator.hardwareConcurrency ?? "unknown");
// Good: direct feature detection instead of userAgent parsing
async function copySnippet(text) {
if (!navigator.clipboard?.writeText) {
console.warn("Clipboard API unavailable in this context.");
return false;
}
await navigator.clipboard.writeText(text);
return true;
}
console.log("Clipboard API present:", Boolean(navigator.clipboard));
Common Mistakes to Avoid
- Calling
navigator.clipboard.writeText()on insecurehttp://pages: Clipboard and Geolocation APIs require HTTPS (orlocalhostduring development) and user interaction. - Trusting
navigator.onLine === trueas proof of internet access:navigator.onLineonly confirms a local network interface is connected; actual internet requests can still time out. - Using deprecated
navigator.platformorappVersion: Rely on CSS media queries for layout and feature checks ("geolocation" in navigator) for APIs.
Frequently Asked Questions
How do I copy code blocks to the clipboard in modern JavaScript?
Call await navigator.clipboard.writeText(code) inside a button click handler wrapped in try...catch in case permissions are denied.
Why is navigator.userAgent unreliable today?
Modern browsers freeze or reduce userAgent details to protect user privacy, and many browsers include "Safari" or "Chrome" tokens inside each other's strings.
What does navigator.sendBeacon(url, data) do?
sendBeacon() sends small analytics payloads asynchronously when a user closes or leaves a tab without delaying page navigation.
Unlock Your
Full Potential.
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With
Try it Yourself
Experiment with the code from this lesson in our interactive playground.