Battery percentage display

I know this is an old post, but for anyone who is interested, using the JS injection method by @victordcq from here:

You can use the Javascript battery API to retrieve the

Here is a bit of sample code:


	code = """<img style='display:none' 
	     src='/favicon.ico' 
	     onload="
	     
		     const jsInjectNode = document.getElementById('jsInjectBatteryMonitor');
		     
		     const dataComponentPath = jsInjectNode.getAttributeNode('data-component-path').value;
		     let view = [...window.__client.page.views._data.values()].find(
		       (view) => view.value.mountPath == dataComponentPath.split('.')[0]
		     ).value;
		     
		     function updateBatteryUI(battery) {
		       console.log('Battery Changed', battery);
		       view.custom.write('battery.level', (battery.level * 100));
		       view.custom.write('battery.charging', battery.charging);
		       view.custom.write('battery.chargingTime', battery.chargingTime);
		       view.custom.write('battery.dischargeTime', battery.dischargingTime);
		     }
		     
		     function monitorBattery(battery) {
		       updateBatteryUI(battery);
		       battery.addEventListener('levelchange',updateBatteryUI.bind(null, battery));
		       battery.addEventListener('chargingchange',updateBatteryUI.bind(null, battery));
		       battery.addEventListener('dischargingtimechange',updateBatteryUI.bind(null, battery));
		       battery.addEventListener('chargingtimechange',updateBatteryUI.bind(null, battery));
		     }
		     
		     if ('getBattery' in window.navigator) {
		       navigator.getBattery().then(monitorBattery);
		     } else {
		       console.log('The Battery Status API is not supported on ' +'this platform.');
		     }
	     
	       ">
	</img>""".replace("\n", "").replace("\t", "")

If you place this in a markdown component in a new view and add the following custom props, you can create yourself a little embeddable battery monitor.

image

image

image

Keep in mind you need to be using HTTPS, not HTTP in order to use the Battery Status API.

4 Likes