Unlocking Device Sensors in the Browser: A Practical Guide to the Generic Sensor API
This article explains why a unified Generic Sensor API is needed, lists the sensors it supports, and provides step‑by‑step JavaScript examples for creating, configuring, and using sensors such as gyroscope, accelerometer, ambient light, magnetometer, and composite orientation sensors, while also covering privacy considerations and future extensions.
Purpose of the Generic Sensor API
The Generic Sensor API defines a single, consistent, low‑level interface for accessing a wide range of device sensors. By unifying the API surface, code can be reused across sensors and new sensor classes can be added without breaking existing code.
Supported sensor classes
Accelerometer
LinearAccelerationSensor
GravitySensor (draft)
Gyroscope
AmbientLightSensor (disabled by default in Chrome)
Magnetometer
AbsoluteOrientationSensor
RelativeOrientationSensor
DeviceOrientationSensor (future drafts)
Chrome enables Accelerometer, Gyroscope, LinearAccelerationSensor, AbsoluteOrientationSensor and RelativeOrientationSensor by default (since version 67). AmbientLightSensor and Magnetometer must be enabled via chrome://flags → Generic Sensor Extra Classes.
Common usage pattern
All sensors follow the same four‑step workflow:
Create the sensor instance.
Register event listeners (usually for the reading event).
Start the sensor.
Stop the sensor when it is no longer needed.
Creating a sensor
let sensor = new Accelerometer(); // replace Accelerometer with any supported classRegistering callbacks
sensor.addEventListener('reading', () => {
// Access sensor data via sensor.x, sensor.y, sensor.z, etc.
});
sensor.addEventListener('error', e => {
console.error(e.error.name, e.error.message);
});Starting and stopping
sensor.start(); sensor.stop();Sensor‑specific examples
Gyroscope
Measures angular velocity around the device’s X, Y, Z axes (rad/s).
let sensor = new Gyroscope();
sensor.addEventListener('reading', () => {
document.getElementById('status').textContent =
`x: ${sensor.x} y: ${sensor.y} z: ${sensor.z}`;
});
sensor.start();Demo URL: https://mobiforge.gitlab.io/sensors/gyroscope.html
Accelerometer (and subclasses)
Provides linear acceleration on X, Y, Z. The LinearAccelerationSensor excludes gravity; GravitySensor reports only gravity (not yet implemented in Chrome).
let sensor = new Accelerometer();
sensor.addEventListener('reading', () => {
document.getElementById('status').textContent =
`x: ${sensor.x} y: ${sensor.y} z: ${sensor.z}`;
});
sensor.start();Demo URL: https://mobiforge.gitlab.io/sensors/accelerometer.html
Ambient Light Sensor
Reports illuminance in lux (approximately 0–30000). The sensor must be enabled via chrome://flags before use.
let sensor = new AmbientLightSensor();
sensor.addEventListener('reading', () => {
document.getElementById('status').textContent = sensor.illuminance;
});
sensor.start();Demo URL: https://mobiforge.gitlab.io/sensors/ambientlight.html
Magnetometer (Compass)
Measures magnetic field on X, Y, Z axes. A simple heading can be derived with Math.atan2 and conversion to degrees.
let sensor = new Magnetometer();
sensor.addEventListener('reading', () => {
let heading = Math.atan2(sensor.y, sensor.x) * (180 / Math.PI);
if (heading < 0) heading += 360;
document.getElementById('status').textContent = `Heading: ${heading}`;
});
sensor.start();Demo URL: https://mobiforge.gitlab.io/sensors/magnetometer.html
Composite orientation sensors
AbsoluteOrientationSensor reports rotation in world coordinates; RelativeOrientationSensor reports rotation relative to a fixed device frame. Both expose a quaternion property (array [x, y, z, w]) suitable for WebGL or Three.js.
let sensor = new AbsoluteOrientationSensor({frequency: 60});
sensor.addEventListener('reading', e => {
const q = e.target.quaternion; // [x, y, z, w]
// Convert quaternion to Euler angles if needed
});
sensor.start();Quaternion‑based compass
Using the quaternion from AbsoluteOrientationSensor, the X‑axis Euler angle yields a tilt‑independent heading.
let sensor = new AbsoluteOrientationSensor();
sensor.addEventListener('reading', e => {
const q = e.target.quaternion;
const heading = Math.atan2(
2 * q[0] * q[1] + 2 * q[2] * q[3],
1 - 2 * (q[1] * q[1] + q[2] * q[2])
) * (180 / Math.PI);
const normalized = heading < 0 ? heading + 360 : heading;
document.getElementById('compass').style.transform = `rotate(${normalized}deg)`;
});
sensor.start();Demo URL: https://mobiforge.gitlab.io/sensors/fusioncompass.html
Privacy and permissions
The Generic Sensor API integrates with the Permissions API. Some browsers may grant access without prompting, but this depends on the sensor and implementation. Current Chrome implementations do not require explicit user consent for the sensors demonstrated here.
Discussion about sensor permissions: https://github.com/w3c/sensors/issues/174
Current state and outlook
Chrome is currently the only major browser offering the Generic Sensor API. Support for many sensors (e.g., GeolocationSensor) remains in draft form. Wider adoption and inclusion of location data are required for the API to become a truly universal sensor interface.
Resources
Specification: https://www.w3.org/TR/generic-sensor/
Gyroscope: https://www.w3.org/TR/gyroscope/
Magnetometer: https://www.w3.org/TR/magnetometer/
Ambient Light: https://www.w3.org/TR/ambient-light/
Accelerometer: https://www.w3.org/TR/accelerometer/
Orientation Sensor: https://www.w3.org/TR/orientation-sensor/
Geolocation Sensor (draft): https://wicg.github.io/geolocation-sensor/
Proximity Sensor: https://www.w3.org/TR/proximity/
Live demos and source code: https://mobiforge.gitlab.io/sensors/ and https://gitlab.com/mobiforge/sensors/
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
