diff --git a/example.js b/example.js index 63c927f..9d1fa1f 100644 --- a/example.js +++ b/example.js @@ -237,6 +237,12 @@ client.on('group_update', (notification) => { console.log('update', notification); }); +client.on('change_battery', (batteryInfo) => { + // Battery percentage for attached device has changed + const { battery, plugged } = batteryInfo; + console.log(`Battery: ${battery}% - Charging? ${plugged}`); +}); + client.on('disconnected', (reason) => { console.log('Client was logged out', reason); }); diff --git a/src/Client.js b/src/Client.js index b688a35..6dec95c 100644 --- a/src/Client.js +++ b/src/Client.js @@ -29,6 +29,7 @@ const { ClientInfo, Message, MessageMedia, Contact, Location, GroupNotification * @fires Client#group_update * @fires Client#disconnected * @fires Client#change_state + * @fires Client#change_battery */ class Client extends EventEmitter { constructor(options = {}) { @@ -296,6 +297,20 @@ class Client extends EventEmitter { } }); + await page.exposeFunction('onBatteryStateChangedEvent', (state) => { + + const { battery, plugged } = state; + + /** + * Emitted when the battery percentage for the attached device changes + * @event Client#change_battery + * @param {object} batteryInfo + * @param {number} batteryInfo.battery - The current battery percentage + * @param {boolean} batteryInfo.plugged - Indicates if the phone is plugged in (true) or not (false) + */ + this.emit(Events.BATTERY_CHANGED, { battery, plugged }); + }); + await page.evaluate(() => { window.Store.Msg.on('add', (msg) => { if(msg.isNewMsg) window.onAddMessageEvent(msg); }); window.Store.Msg.on('change', (msg) => { window.onChangeMessageEvent(msg); }); @@ -304,6 +319,7 @@ class Client extends EventEmitter { window.Store.Msg.on('change:isUnsentMedia', (msg, unsent) => { if(msg.id.fromMe && !unsent) window.onMessageMediaUploadedEvent(msg); }); window.Store.Msg.on('remove', (msg) => { if(msg.isNewMsg) window.onRemoveMessageEvent(msg); }); window.Store.AppState.on('change:state', (_AppState, state) => { window.onAppStateChangedEvent(state); }); + window.Store.Conn.on('change:battery', (state) => { window.onBatteryStateChangedEvent(state); }); }); /** diff --git a/src/util/Constants.js b/src/util/Constants.js index d25903f..48434cc 100644 --- a/src/util/Constants.js +++ b/src/util/Constants.js @@ -46,6 +46,7 @@ exports.Events = { QR_RECEIVED: 'qr', DISCONNECTED: 'disconnected', STATE_CHANGED: 'change_state', + BATTERY_CHANGED: 'change_battery' }; /**