The Sensor APIs are a set of interfaces built to a common design that expose device sensors in a consistent way to the web platform.

Sensor APIs Concepts and Usage

Although the Generic Sensor API specification defines a 传感器 interface, as a web developer you will never use it. Instead you'll use one of its subclasses to retrieve specific kinds of sensor data. For example, the accelerometer interface returns the acceleration of the device along all three axes at the time it is read.

Sensors may or may not correspond exactly to a physical device sensor. For example, the Gyroscope interface corresponds exactly to a physical device interface. Alternatively, the AbsoluteOrientationSensor interface provides information that is algorithmically agregated from two or more device sensors. These sensor types are referred to as 低级 and 高级 respectively. The latter type of sensor is also called a fusion sensor (alternatively, virtual or synthetic sensors).

特征检测

Sensor interfaces are only proxies for the underlying device sensors. Consequently, feature detection is more complicated for sensors than it is for other APIs. The presence of a sensor API does not tell you whether that API is connected to a real hardware sensor, whether that sensor works, if it's still connected, or even whether the user has granted access to it. Making all this information consistently available is costly to performance and battery life.

Therefore, feature detection for sensor APIs must include both detection of the APIs themselves and defensive programming strategies (see below) .

The examples below show three methods for detecting sensor APIs. Additionally you can put object instantiation inside a try...catch block. Notice that detection through the Navigator interface is not one of the available options.

if (typeof Gyroscope === "function") {
    // run in circles...
}
if ("ProximitySensor" in window) {
    // watch out!
}
if (window.AmbientLightSensor) {
    // go dark...
}
					

防御性编程

As stated in Feature Detection, checking for a particular sensor API is insufficient for feature detection. The existence of an actual sensor must be confirmed as well. This is where defensive programming is needed. Defensive programming requires three strategies.

  • Checking for thrown errors when instantiating a sensor object.
  • Listening for errors thrown during its use.
  • Handling the errors gracefully so that the user experience is enhanced rather than degraded.

The code example below illustrates these principles. The try...catch block catches errors thrown during sensor instantiation. It implements a handler for Sensor.onerror to catch errors thrown during use. The only time anything is shown to the user is when permissions need to be requested and when the sensor type isn't supported by the device.

If a feature policy blocks use of a feature it is because your code is inconsistent with the policies set on your server. This is not something that would ever be shown to a user. See Feature-Policy for implementation instructions.

let accelerometer = null;
try {
    accelerometer = new Accelerometer({ referenceFrame: 'device' });
    accelerometer.addEventListener('error', event => {
        // Handle runtime errors.
        if (event.error.name === 'NotAllowedError') {
            // Branch to code for requesting permission.
        } else if (event.error.name === 'NotReadableError' ) {
            console.log('Cannot connect to the sensor.');
        }
    });
    accelerometer.addEventListener('reading', () => reloadOnShake(accelerometer));
    accelerometer.start();
} catch (error) {
    // Handle construction errors.
    if (error.name === 'SecurityError') {
        // See the note above about feature policy.
        console.log('Sensor construction was blocked by a feature policy.');
    } else if (error.name === 'ReferenceError') {
        console.log('Sensor is not supported by the User Agent.');
    } else {
        throw error;
    }
}
					

Permissions and Feature Policy

Sensor readings may not be taken unless the user grants permission to a specific sensor type. Do this using the 权限 API. A brief example, shown below, requests permission before attempting to use the sensor.

navigator.permissions.query({ name: 'accelerometer' })
.then(result => {
  if (result.state === 'denied') {
    console.log('Permission to use accelerometer sensor is denied.');
    return;
  }
  // Use the sensor.
});
					

An alternative approach is to attempt to use the error and listen for the SecurityError .

const sensor = new AbsoluteOrientationSensor();
sensor.start();
sensor.onerror = event => {
  if (event.error.name === 'SecurityError')
    console.log("No permissions to use AbsoluteOrientationSensor.");
};
					

The following table describes for each sensor type, the name required for the Permissions API, the <iframe> 元素的 allow attribute and the Feature-Policy 指令。

Sensor permissions
传感器 Permission/Feature Policy Name
AbsoluteOrientationSensor 'accelerometer' , 'gyroscope' ,和 'magnetometer'
Accelerometer 'accelerometer'
AmbientLightSensor 'ambient-light-sensor'
Gyroscope 'gyroscope'
LinearAccelerationSensor 'accelerometer'
Magnetometer 'magnetometer'
RelativeOrientationSensor 'accelerometer' ,和 'gyroscope'

Readings

Sensor readings are received through the Sensor.onreading callback which is inherited by all sensor types. Reading frequency is decided by you, accomplished with an option passed to a sensor's constructor. The option is a number that specifies the number of readings per second. A whole number or decimal may be used, the latter for frequencies less than a second. The actual reading frequency depends device hardware and consequently may be less than requested.

The following example illustrates this using the Magnetometer sensor.

let magSensor = new Magnetometer({frequency: 60});
magSensor.addEventListener('reading', e => {
  console.log("Magnetic field along the X-axis " + magSensor.x);
  console.log("Magnetic field along the Y-axis " + magSensor.y);
  console.log("Magnetic field along the Z-axis " + magSensor.z);
})
magSensor.addEventListener('error', event => {
  console.log(event.error.name, event.error.message);
})
magSensor.start();
					

接口

AbsoluteOrientationSensor 安全上下文

Describes the device's physical orientation in relation to the Earth's reference coordinate system.

Accelerometer 安全上下文

Provides the acceleration applied to the device along all three axes.

AmbientLightSensor 安全上下文

Returns the current light level or illuminance of the ambient light around the hosting device.

Gyroscope 安全上下文

Provides the angular velocity of the device along all three axes.

LinearAccelerationSensor 安全上下文

Provides the acceleration applied to the device along all three axes, but without the contribution of gravity.

Magnetometer 安全上下文

Provides information about the magnetic field as detected by the device’s primary magnetometer sensor.

OrientationSensor 安全上下文
The base class for the AbsoluteOrientationSensor . This interface cannot be used directly, instead it provides properties and methods accessed by interfaces that inherit from it.
RelativeOrientationSensor 安全上下文

Describes the device's physical orientation without regard to the Earth's reference coordinate system.

传感器 安全上下文

The base class for all the other sensor interfaces. This interface cannot be used directly. Instead it provides properties, event handlers, and methods accessed by interfaces that inherit from it.

SensorErrorEvent 安全上下文
Provides information about errors thrown by a 传感器 or related interface.

规范

规范 状态 注释
Generic Sensor API 候选推荐 初始定义。
Accelerometer 候选推荐 定义 Accelerometer and LinearAccerationSensor .
Ambient Light Sensor 候选推荐
Gyroscope 候选推荐 初始定义。
Magnetometer 候选推荐
Orientation Sensor 候选推荐 定义 AbsoluteOrientationSensor and RelativeOrientationSensor .

浏览器兼容性

The compatibility table in this page is generated from structured data. If you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request. 更新 GitHub 上的兼容性数据
桌面 移动
Chrome Edge Firefox Internet Explorer Opera Safari Android webview Chrome for Android Firefox for Android Opera for Android Safari on iOS Samsung Internet
传感器 Chrome 69 Edge ≤79 Firefox ? IE ? Opera 56 Safari ? WebView Android 69 Chrome Android 69 Firefox Android ? Opera Android 48 Safari iOS ? Samsung Internet Android 10.0
activated Chrome 69 Edge ≤79 Firefox ? IE ? Opera 56 Safari ? WebView Android 69 Chrome Android 69 Firefox Android ? Opera Android 48 Safari iOS ? Samsung Internet Android 10.0
hasReading Chrome 69 Edge ≤79 Firefox ? IE ? Opera 56 Safari ? WebView Android 69 Chrome Android 69 Firefox Android ? Opera Android 48 Safari iOS ? Samsung Internet Android 10.0
onactivate Chrome 69 Edge ≤79 Firefox ? IE ? Opera 56 Safari ? WebView Android 69 Chrome Android 69 Firefox Android ? Opera Android 48 Safari iOS ? Samsung Internet Android 10.0
onerror Chrome 69 Edge ≤79 Firefox ? IE ? Opera 56 Safari ? WebView Android 69 Chrome Android 69 Firefox Android ? Opera Android 48 Safari iOS ? Samsung Internet Android 10.0
onreading Chrome 69 Edge ≤79 Firefox ? IE ? Opera 56 Safari ? WebView Android 69 Chrome Android 69 Firefox Android ? Opera Android 48 Safari iOS ? Samsung Internet Android 10.0
start Chrome 69 Edge ≤79 Firefox ? IE ? Opera 56 Safari ? WebView Android 69 Chrome Android 69 Firefox Android ? Opera Android 48 Safari iOS ? Samsung Internet Android 10.0
stop Chrome 69 Edge ≤79 Firefox ? IE ? Opera 56 Safari ? WebView Android 69 Chrome Android 69 Firefox Android ? Opera Android 48 Safari iOS ? Samsung Internet Android 10.0
timestamp Chrome 69 Edge ≤79 Firefox ? IE ? Opera 56 Safari ? WebView Android 69 Chrome Android 69 Firefox Android ? Opera Android 48 Safari iOS ? Samsung Internet Android 10.0

图例

完整支持

完整支持

兼容性未知 ?

兼容性未知

元数据

  • 最后修改:
  1. Sensor_APIs