阿里云主机折上折
  • 微信号
Current Site:Index > navigator object properties

navigator object properties

Author:Chuan Chen 阅读数:64851人阅读 分类: JavaScript

The navigator object is one of the global objects provided by the browser environment, used to retrieve information about the current browser. It contains numerous properties and methods that help developers detect browser type, version, operating system, and even implement specific functionalities such as geolocation or clipboard operations.

navigator.userAgent

The userAgent property returns a string representing the browser's user agent header. By parsing this string, you can determine the browser type, version, and operating system.

console.log(navigator.userAgent);
// Example output: "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36"

In practice, browser detection can be achieved using regular expressions:

const isChrome = /Chrome/i.test(navigator.userAgent) && !/Edge/i.test(navigator.userAgent);
console.log(`Currently ${isChrome ? 'is' : 'is not'} Chrome browser`);

navigator.platform

This property returns the operating system platform on which the browser is running, such as Win32, MacIntel, or Linux x86_64.

console.log(navigator.platform); // Example output: "Win32"

Note: Modern browsers may return an empty string or vague values to enhance privacy protection.

navigator.language

Returns the browser's preferred language setting, formatted as a BCP 47 language tag. For example, zh-CN represents Simplified Chinese.

console.log(navigator.language); // Example output: "zh-CN"

Multilingual websites often use this property to implement automatic language switching:

if (navigator.language.startsWith('zh')) {
  document.documentElement.lang = 'zh';
}

navigator.cookieEnabled

A boolean property indicating whether the browser has cookies enabled.

if (!navigator.cookieEnabled) {
  alert('Please enable cookies to ensure the website functions properly');
}

navigator.onLine

Returns a boolean indicating whether the browser is online. Note: Even if it returns true, it does not guarantee access to a specific server.

window.addEventListener('online', () => {
  console.log('Network restored');
});
window.addEventListener('offline', () => {
  console.log('Network disconnected');
});

navigator.geolocation

Provides an interface to access the device's geolocation information, requiring user authorization.

navigator.geolocation.getCurrentPosition(
  position => {
    console.log('Latitude:', position.coords.latitude);
    console.log('Longitude:', position.coords.longitude);
  },
  error => {
    console.error('Failed to get location:', error.message);
  }
);

navigator.clipboard

A modern clipboard API supporting read and write operations. Must be called in a secure context (HTTPS) and after user interaction.

// Write text
document.getElementById('copyBtn').addEventListener('click', async () => {
  try {
    await navigator.clipboard.writeText('Text to copy');
    console.log('Copy successful');
  } catch (err) {
    console.error('Copy failed:', err);
  }
});

// Read text
document.getElementById('pasteBtn').addEventListener('click', async () => {
  try {
    const text = await navigator.clipboard.readText();
    console.log('Pasted content:', text);
  } catch (err) {
    console.error('Failed to read clipboard:', err);
  }
});

navigator.mediaDevices

Provides an interface to access media devices (e.g., camera, microphone), returning a Promise.

// Access user media devices
navigator.mediaDevices.getUserMedia({ video: true, audio: false })
  .then(stream => {
    document.getElementById('video').srcObject = stream;
  })
  .catch(err => {
    console.error('Failed to access media devices:', err);
  });

navigator.hardwareConcurrency

Returns the number of logical processor cores on the device, useful for optimizing Web Worker count.

const workerCount = Math.min(navigator.hardwareConcurrency || 4, 8);
console.log(`Recommended to create ${workerCount} Web Workers`);

navigator.storage

Provides storage management APIs to query available storage space and other information.

navigator.storage.estimate().then(estimate => {
  console.log(`Used space: ${estimate.usage} bytes`);
  console.log(`Total space: ${estimate.quota} bytes`);
});

navigator.deviceMemory

Returns the device's memory size (GB), which may be rounded or return a lower value for privacy reasons.

if (navigator.deviceMemory < 2) {
  console.log('Low-memory device, enabling simplified mode');
}

navigator.vendor

Returns browser vendor information, such as Google Inc. or Apple Computer, Inc..

console.log(navigator.vendor); // Chrome output: "Google Inc."

navigator.doNotTrack

Returns whether the user has enabled the "Do Not Track" (DNT) preference. May return 1 (enabled), 0 (disabled), or null (not set).

if (navigator.doNotTrack === '1') {
  console.log('User has enabled Do Not Track');
}

navigator.connection

Provides network connection information, including type and speed.

const connection = navigator.connection || navigator.mozConnection || navigator.webkitConnection;
if (connection) {
  console.log('Connection type:', connection.type);
  console.log('Effective type:', connection.effectiveType);
  console.log('Download speed (Mbps):', connection.downlink);
  console.log('Round-trip time (ms):', connection.rtt);
}

navigator.permissions

A permissions query API to check the status of various permissions.

navigator.permissions.query({ name: 'geolocation' }).then(result => {
  console.log(`Geolocation permission status: ${result.state}`);
});

navigator.getBattery()

Returns a Promise resolving to battery status information.

navigator.getBattery().then(battery => {
  console.log(`Battery level: ${battery.level * 100}%`);
  console.log(`Charging status: ${battery.charging ? 'Charging' : 'Not charging'}`);
});

navigator.plugins

Returns an array of installed plugins, though modern browsers may restrict this property.

Array.from(navigator.plugins).forEach(plugin => {
  console.log(`Plugin name: ${plugin.name}, version: ${plugin.version}`);
});

navigator.mimeTypes

Returns an array of MIME types supported by the browser.

Array.from(navigator.mimeTypes).forEach(mimeType => {
  console.log(`MIME type: ${mimeType.type}, description: ${mimeType.description}`);
});

navigator.javaEnabled()

Returns a boolean indicating whether Java is enabled in the browser.

console.log(`Java ${navigator.javaEnabled() ? 'enabled' : 'disabled'}`);

navigator.sendBeacon()

Asynchronously sends small amounts of data to a server, ideal for sending logs during page unload.

window.addEventListener('unload', () => {
  const data = new Blob([JSON.stringify({ event: 'page_close' })], { type: 'application/json' });
  navigator.sendBeacon('/log', data);
});

本站部分内容来自互联网,一切版权均归源网站或源作者所有。

如果侵犯了你的权益请来信告知我们删除。邮箱:cc@cccx.cn

上一篇:事件监听模式

下一篇:screen对象信息

Front End Chuan

Front End Chuan, Chen Chuan's Code Teahouse 🍵, specializing in exorcising all kinds of stubborn bugs 💻. Daily serving baldness-warning-level development insights 🛠️, with a bonus of one-liners that'll make you laugh for ten years 🐟. Occasionally drops pixel-perfect romance brewed in a coffee cup ☕.