HTML Device APIs
Access device hardware and sensors from web browsers
📱 What are Device APIs?
Device APIs allow web applications to interact with device hardware like cameras, microphones, sensors, and more. Create native-like experiences in the browser!
// Access device camera
const stream = await navigator.mediaDevices.getUserMedia({
video: true,
audio: true
});
// Get device orientation
window.addEventListener('deviceorientation', (event) => {
console.log('Alpha:', event.alpha);
console.log('Beta:', event.beta);
console.log('Gamma:', event.gamma);
});
Try it:
Device API Categories
Media Devices
Camera, microphone, and screen capture
navigator.mediaDevices.getUserMedia({
video: true, audio: true
});
Sensors
Orientation, motion, and ambient light
window.addEventListener('deviceorientation',
(e) => console.log(e.alpha)
);
Battery Status
Monitor device battery information
navigator.getBattery().then(battery => {
console.log(battery.level);
});
Vibration
Provide haptic feedback
navigator.vibrate([200, 100, 200]);
🔹 Camera and Microphone Access
Access device media with the MediaDevices API:
// Request camera and microphone access
async function startCamera() {
try {
const stream = await navigator.mediaDevices.getUserMedia({
video: {
width: { ideal: 1280 },
height: { ideal: 720 },
facingMode: 'user' // 'user' for front camera, 'environment' for back
},
audio: {
echoCancellation: true,
noiseSuppression: true
}
});
// Display video stream
const video = document.getElementById('videoElement');
video.srcObject = stream;
return stream;
} catch (error) {
console.error('Error accessing media devices:', error);
if (error.name === 'NotAllowedError') {
alert('Camera access denied by user');
} else if (error.name === 'NotFoundError') {
alert('No camera found on this device');
}
}
}
// Stop camera stream
function stopCamera(stream) {
stream.getTracks().forEach(track => {
track.stop();
});
}
// Get available cameras
async function getCameras() {
try {
const devices = await navigator.mediaDevices.enumerateDevices();
const cameras = devices.filter(device => device.kind === 'videoinput');
return cameras;
} catch (error) {
console.error('Error getting cameras:', error);
}
}
Try it:
📷
🔹 Device Orientation and Motion
Detect device movement and orientation:
// Device orientation (compass direction)
window.addEventListener('deviceorientation', (event) => {
const alpha = event.alpha; // Z-axis rotation (0-360°)
const beta = event.beta; // X-axis rotation (-180 to 180°)
const gamma = event.gamma; // Y-axis rotation (-90 to 90°)
console.log(`Orientation - Alpha: ${alpha}, Beta: ${beta}, Gamma: ${gamma}`);
// Update UI based on orientation
updateCompass(alpha);
updateTiltIndicator(beta, gamma);
});
// Device motion (acceleration)
window.addEventListener('devicemotion', (event) => {
const acceleration = event.acceleration;
const rotationRate = event.rotationRate;
if (acceleration) {
console.log(`Acceleration - X: ${acceleration.x}, Y: ${acceleration.y}, Z: ${acceleration.z}`);
}
if (rotationRate) {
console.log(`Rotation - Alpha: ${rotationRate.alpha}, Beta: ${rotationRate.beta}, Gamma: ${rotationRate.gamma}`);
}
});
// Request permission for iOS devices
async function requestMotionPermission() {
if (typeof DeviceOrientationEvent.requestPermission === 'function') {
const permission = await DeviceOrientationEvent.requestPermission();
return permission === 'granted';
}
return true; // Android devices don't need permission
}
Try it:
🧭 Compass
0°
📱 Tilt
Level
🔹 Vibration and Battery APIs
Provide haptic feedback and monitor battery status:
// Vibration API
function vibrate(pattern) {
if ('vibrate' in navigator) {
navigator.vibrate(pattern);
} else {
console.log('Vibration not supported');
}
}
// Different vibration patterns
function shortVibration() {
vibrate(200); // Single 200ms vibration
}
function longVibration() {
vibrate(1000); // Single 1000ms vibration
}
function patternVibration() {
vibrate([100, 50, 100, 50, 300]); // Pattern: vibrate, pause, vibrate, pause, long vibrate
}
// Battery API (deprecated but still available in some browsers)
async function getBatteryInfo() {
try {
if ('getBattery' in navigator) {
const battery = await navigator.getBattery();
console.log('Battery level:', (battery.level * 100) + '%');
console.log('Charging:', battery.charging);
console.log('Charging time:', battery.chargingTime);
console.log('Discharging time:', battery.dischargingTime);
// Listen for battery events
battery.addEventListener('chargingchange', () => {
console.log('Charging status changed:', battery.charging);
});
battery.addEventListener('levelchange', () => {
console.log('Battery level changed:', (battery.level * 100) + '%');
});
return battery;
} else {
console.log('Battery API not supported');
}
} catch (error) {
console.error('Error getting battery info:', error);
}
}
Try it:
📳 Vibration
🔋 Battery
Level:
--
Status:
--