From d34dada9d8c2ace69defdbecd3fa8f4bb1fb65bc Mon Sep 17 00:00:00 2001 From: Tommy Jonsson Date: Sat, 12 Jan 2019 05:35:10 +0100 Subject: [PATCH] Allow push notifications to suggest its device name (#2446) * Allow push notifications to suggest its device name * Lint --- .../ha-push-notifications-toggle.js | 21 ++++++++++++++----- 1 file changed, 16 insertions(+), 5 deletions(-) diff --git a/src/components/ha-push-notifications-toggle.js b/src/components/ha-push-notifications-toggle.js index e024cc4c01..d5078f6978 100644 --- a/src/components/ha-push-notifications-toggle.js +++ b/src/components/ha-push-notifications-toggle.js @@ -20,6 +20,7 @@ class HaPushNotificationsToggle extends EventsMixin(PolymerElement) { `; } @@ -35,7 +36,6 @@ class HaPushNotificationsToggle extends EventsMixin(PolymerElement) { type: Boolean, value: "Notification" in window && Notification.permission === "granted", - observer: "handlePushChange", }, loading: { type: Boolean, @@ -63,12 +63,12 @@ class HaPushNotificationsToggle extends EventsMixin(PolymerElement) { } } - handlePushChange(pushChecked) { + handlePushChange(event) { // Somehow this is triggered on Safari on page load causing // it to get into a loop and crash the page. if (!pushSupported) return; - if (pushChecked) { + if (event.target.checked) { this.subscribePushNotifications(); } else { this.unsubscribePushNotifications(); @@ -77,10 +77,9 @@ class HaPushNotificationsToggle extends EventsMixin(PolymerElement) { async subscribePushNotifications() { const reg = await navigator.serviceWorker.ready; + let sub; try { - const sub = await reg.pushManager.subscribe({ userVisibleOnly: true }); - let browserName; if (navigator.userAgent.toLowerCase().indexOf("firefox") > -1) { browserName = "firefox"; @@ -88,12 +87,24 @@ class HaPushNotificationsToggle extends EventsMixin(PolymerElement) { browserName = "chrome"; } + const name = prompt("What should this device be called ?"); + if (name == null) { + this.pushChecked = false; + return; + } + + sub = await reg.pushManager.subscribe({ userVisibleOnly: true }); + await this.hass.callApi("POST", "notify.html5", { subscription: sub, browser: browserName, + name, }); } catch (err) { const message = err.message || "Notification registration failed."; + if (sub) { + await sub.unsubscribe(); + } // eslint-disable-next-line console.error(err);