Vous êtes sur la page 1sur 7

22/9/2016

9JavaScriptAPIsaccessingDeviceHardware

Back

Blog Resources

9 JavaScript APIs accessing Device


Hardware
Published last year by Mate Marschalko
My RC car and my desk plant both have an Arduino microcontroller onboard and I
used a Node.js server to interface with them through the USB port. This is a great
way to build prototypes and toys for yourself but sometimes you want your demos
to work on regular phones or laptops in the browser without extra hardware or
software. This is why its worth exploring all the available, native HTML5 and
JavaScript APIs that allow us to access hardware components and sensors in our
devices.

Phone Calls and Text Messages


http://www.webondevices.com/9javascriptapisaccessingdevicesensors/

1/7

22/9/2016

9JavaScriptAPIsaccessingDeviceHardware

The most important features of our mobile devices are obviously making phone calls

andBack
sending text messages. It is actually possible with pure HTML toBlog
start aResources
call and
compose a text message by simply adding a special href value where normally
regular Download
URLs go. Pure
HTML
magic!
FREE
Ebook:
Introduction to JavaScript Electronics

<ahref="tel:+44703567387625">
Callnumber!
</a>
<ahref="sms:+44703567387625?body=Hello%20there!">
ComposeSMS!
</a>

Geolocation API
The geolocation API gives you information about the location of the user. There are
multiple ways for the browser to get this data and some are more accurate than
others (GPS vs. GSM or Wi-Fi). The navigator.geolocation object is what we use to
retrieve the global latitude and longitude position.
Browser support of the Geolocation API is greate. Even IE9 handles it.

//Checksupport
if(navigator.geolocation){
navigator.geolocation.getCurrentPosition(success);
}
functionsuccess(position){
console.log('Latitude:'+position.coords.latitude);
console.log('Longitude:'+position.coords.longitude);
}

Device Orientation and Device Motion API


The Device Orientation API accesses the built in gyroscope and compass of your
device and can tell you the rotation angle of it in three dimension.

if(window.DeviceOrientationEvent){
window.addEventListener('deviceorientation',function(eventData){
http://www.webondevices.com/9javascriptapisaccessingdevicesensors/

2/7

22/9/2016

9JavaScriptAPIsaccessingDeviceHardware

//gammaisthelefttorighttiltindegrees
Back
console.log(eventData.gamma);

Blog Resources

//betaisthefronttobacktiltindegrees
Download FREE Ebook: Introduction to JavaScript Electronics
console.log(eventData.beta);
//alphaisthecompassdirectionthedeviceisfacingindegrees
console.log(eventData.alpha);
},false);
}

Device Motion API on the other hand uses the accelerometer to tell when the device
moves or rotates into any direction. Keep in mind that it only detects acceleration
and not the speed.

if(window.DeviceMotionEvent){
window.addEventListener('devicemotion',function(eventData){
//Acceleration
console.log(eventData.acceleration.x);
console.log(eventData.acceleration.y);
console.log(eventData.acceleration.z);

//Accelerationincludinggravity
console.log(eventData.accelerationIncludingGravity.x);
console.log(eventData.accelerationIncludingGravity.y);
console.log(eventData.accelerationIncludingGravity.z);
//Rotationrate
console.log(eventData.rotationRate.alpha);
console.log(eventData.rotationRate.beta);
console.log(eventData.rotationRate.gamma);
},false);
}

Browser support on both of these APIs are very good. There are no problems in iOS
and Android at all and even IE for Windows Phone started supporting it from version
11.

Vibration API
http://www.webondevices.com/9javascriptapisaccessingdevicesensors/

3/7

22/9/2016

9JavaScriptAPIsaccessingDeviceHardware

The built in vibration motor of your device can be used to give subtle notications to
BlogorResources
theBack
user. It also oers a great way to give haptic feedback when a button
other
element is tapped on the website. Although browser support is not as good as of the
previous
APIs but FREE
it can Ebook:
very easily
be introduced
as a progressive
enhancement. This
Download
Introduction
to JavaScript
Electronics
simply means that it will work on modern browsers but wont break anything on the
ones not supporting it. Android, Chrome, Firefox and Opera all support this.

varvibrate=navigator.vibrate||navigator.mozVibrate;
//vibratefor1second
vibrate(1000);
//vibratefor1second,thenpauseforhalf,thenvibrateforanother1
second
vibrate([1000,500,2000]);

Battery Manager API


There are many ways to use the battery status information on a web app. We can
prevent complex, cpu heavy animations and calculations from running or large
assets from downloading when the battery is low on power. This API worked both on
my laptop and my Android phone in Chrome and it should also work in Firefox and
Opera too.

varbattery=navigator.battery||navigator.webkitBattery||
navigator.mozBattery;
functionlogBattery(battery){
console.log(battery.level);
console.log(battery.charging);
console.log(dischargingTime);
battery.addEventListener('chargingchange',function(){
console.log('Batterychargingchangeevent:'+battery.charging);
},false);
}
if(navigator.getBattery){
navigator.getBattery().then(logBattery);
}elseif(battery){
http://www.webondevices.com/9javascriptapisaccessingdevicesensors/

4/7

22/9/2016

9JavaScriptAPIsaccessingDeviceHardware

logBattery(battery);
}Back

Blog Resources

Download FREE Ebook: Introduction to JavaScript Electronics

Device Light API


This API uses the built in light level sensor of your device and returns the readings in
lux units. Unfortunately, accessing this sensor is only supported in Firefox but its
worth mentioning in case you are setting up a kiosk or tech demo where browser
support doesnt matter.
In the future, when CSS4 support increases, we might also start using the CSS4
light-level media query to change CSS styling when light conditions change. Very
exciting!
In the mean time heres a simple way to get this information with the JavaScript API:

if('ondevicelight'inwindow){
window.addEventListener("devicelight",function(event){
//lightlevelisreturnedinluxunits
console.log(event.value+"lux");
});
}
if('onlightlevel'inwindow){
window.addEventListener("lightlevel",function(event){
//lightvaluecanbedim,normalorbright
console.log(event.value);
});
}

Proximity Events API


The proximity sensor can usually be found on the front of your device and it uses its
measurements to tell when you put your phone against your ear or when you reach
towards it. Its an accurate little sensor so it can tell the distance of any object held in
front of the phone.
Similarly to the Device Light API this one is only support in Firefox.

http://www.webondevices.com/9javascriptapisaccessingdevicesensors/

5/7

22/9/2016

9JavaScriptAPIsaccessingDeviceHardware

if('ondeviceproximity'inwindow){
Back
Blog
//Firedwhenobjectisinthedetectionzone
window.addEventListener('deviceproximity',function(event){
Download FREE Ebook: Introduction to JavaScript Electronics
//Objectdistanceincentimeters
console.log(event.value+"centimeters");

Resources

});
}else{
console.log("deviceproximitynotsupported");
}
if('ondeviceproximity'inwindow){
//Firedwhenobjectisinthedetectionzone
window.addEventListener('userproximity',function(event){
if(event.near==true){
console.log("Objectisnear");
}else{
console.log("Objectisfar");
}
});
}else{
console.log("userproximitynotsupported");
}

Back to all

Leave a Reply
You must be logged in to post a comment.

Free Ebook
Step up your web developer career and learn hardware prototyping.

http://www.webondevices.com/9javascriptapisaccessingdevicesensors/

6/7

22/9/2016

9JavaScriptAPIsaccessingDeviceHardware

This ebook will get you started with JavaScript Arduino electronics development in a
Backof hours.
Blog Resources
couple
Download FREE Ebook: Introduction to JavaScript Electronics
Email address

Send me the PDF

Web on Devices
Electronics Hacking with JavaScript and other Web Technologies
Twitter

Facebook

Mate Marschalko
Front-end Web Developer, Creative Technologist and Maker. Builds Internet connected devices for the Internet of
Things.

All rights reserved | Contact at hello@webondevices.com

http://www.webondevices.com/9javascriptapisaccessingdevicesensors/

7/7

Vous aimerez peut-être aussi