世間では常識でbmが知らなかっただけ、という可能性大だけど・・
W3Cの Device APIにバッテリの消費量を取得する Battery Status API があるらしい
Battery Status API
This specification defines an API that provides information about the battery status of the hosting …
ドキュメントのステータスは Working Draft。
勧告までにはまだいろいろ替わりそうだが軽く予習。
概要
タイトルでは「スマートフォン」と書いたが、introductionには
The Battery Status API specification defines a means for web developers to programmatically determine the battery status of the hosting device.
とあるのでPCにも実装されるかも。
サンプルとしては、JavaScriptで定期的にメールを見に行くのはバカなのでBatteryManagerとうインタフェース(API)をつかってバッテリーの残量が少ない場合はメールを読みに行く間隔を広げましょう、というスクリプトが掲載されている。
var battery = navigator.battery;
battery.addEventListener('dischargingtimechange', function () {
if (battery.dischargingTime < 60 * 30 || battery.level < 0.1) {
mail.setTimer(mail.INTERVAL_BATTERY_LOW);
console.log('30 minutes remaining or level below 10%, checking the server less frequently.');
} else if (battery.dischargingTime < 60 * 10 || battery.level < 0.05) {
mail.setTimer(null);
console.log('10 minutes remaining or level below 5%, stop checking the server.');
}
}, false);
battery.addEventListener('chargingchange', function () {
if (battery.charging) {
mail.setTimer(mail.INTERVAL_DEFAULT);
console.log('Battery is charging, checking the server normally.');
}
}, false);
このあたりが心臓部。
イベントドリブンで残り寿命30分以内若しくは10%の場合は10分おきに、残り寿命10分以内若しくは5%の場合はメールの取得を中止する、と。
Classは2つ
NavigatorBattery と BatteryManager .
基本的にはNavigatorのインスタンスからBatteryManagerのインスタンスを取得して、その値を読んだりイベントを登録したりするだけ。
BatteryManagerの取得
var battery = navigator.battery;
BatteryManagerのプロパティの取得
例)バッテリレベルの取得
console.log(battery.level);
プロパティは以下の通り
readonly attribute boolean charging; //充電中か否か
readonly attribute double chargingTime; //バッテリがフル充電されるまでの時間(単位:秒)バッテリがないデバイスやフル充電時は"0"
readonly attribute double level; //バッテリの残り割合 0.0(空っぽ)〜1.0(フル)
readonly attribute double dischargingTime; //バッテリの残り寿命(単位:秒) 充電中は+無限大
BatteryManagerへのイベントハンドラ登録
例)
battery.addEventListener('dischargingtimechange', function () { bra bra bra});
イベントは以下の通り
attribute Function? onchargingchange;
attribute Function? onchargingtimechange;
attribute Function? onlevelchange;
attribute Function? ondischargingtimechange;
ドキュメントにイベントの説明なし。ハンドラ名から押して測るべし。
実際のサンプルコードは元ドキュメント参照。
はやくMobileSafariに実装されないかしら。
Reference:
Surfin’ Safari – Blog Archive ? Last week in WebKit: Battery Status API and form updates
Read More