-
Notifications
You must be signed in to change notification settings - Fork 2
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
2 changed files
with
69 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,68 @@ | ||
import { useState, useEffect } from "vue-hooks"; | ||
|
||
let unsupported; | ||
|
||
const useBatteryStatus = () => { | ||
// 检查浏览器是否支持 navigator.getBattery | ||
if ("getBattery" in navigator) { | ||
unsupported = false; | ||
} else { | ||
unsupported = true; | ||
} | ||
|
||
const initialBatteryStatus = !unsupported | ||
? { | ||
charging: null, // the charging state of the system's battery | ||
chargingTime: null, // the time remaining in seconds until the system's battery is fully charged | ||
dischargingTime: null, // the time remaining in seconds until the system's battery is completely discharged and the system is about to be suspended | ||
level: null // the level of the system's battery | ||
} | ||
: { | ||
unsupported | ||
}; | ||
|
||
const [batteryStatus, setBatteryStatus] = useState(initialBatteryStatus); | ||
|
||
const updateBatteryStatus = battery => { | ||
setBatteryStatus({ | ||
chargingTime: battery.chargingTime, | ||
dischargingTime: battery.dischargingTime, | ||
level: battery.level, | ||
charging: battery.charging | ||
}); | ||
}; | ||
|
||
useEffect(() => { | ||
if (!unsupported) { | ||
const monitorBattery = battery => { | ||
updateBatteryStatus(battery); | ||
|
||
battery.addEventListener( | ||
"levelchange", | ||
updateBatteryStatus.bind(null, battery) | ||
); | ||
battery.addEventListener( | ||
"chargingchange", | ||
updateBatteryStatus.bind(null, battery) | ||
); | ||
battery.addEventListener( | ||
"dischargingtimechange", | ||
updateBatteryStatus.bind(null, battery) | ||
); | ||
battery.addEventListener( | ||
"chargingtimechange", | ||
updateBatteryStatus.bind(null, battery) | ||
); | ||
}; | ||
|
||
navigator.getBattery().then(monitorBattery); | ||
} | ||
}, []); | ||
|
||
return { | ||
...batteryStatus, | ||
updateBatteryStatus | ||
}; | ||
}; | ||
|
||
export { useBatteryStatus }; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters