From ebe2a951409ccb21d828924860a03c6052abbeb1 Mon Sep 17 00:00:00 2001 From: Egor Kislitsyn Date: Fri, 7 Dec 2018 14:57:35 +0700 Subject: [PATCH] improve web push notifications --- src/modules/users.js | 7 +------ src/services/push/push.js | 10 +++++++++- 2 files changed, 10 insertions(+), 7 deletions(-) diff --git a/src/modules/users.js b/src/modules/users.js index 791f1680..d2c7fdf6 100644 --- a/src/modules/users.js +++ b/src/modules/users.js @@ -1,9 +1,8 @@ import backendInteractorService from '../services/backend_interactor_service/backend_interactor_service.js' +import registerPushNotifications from '../services/push/push.js' import { compact, map, each, merge } from 'lodash' import { set } from 'vue' -import registerPushNotifications from '../services/push/push.js' - // TODO: Unify with mergeOrAdd in statuses.js export const mergeOrAdd = (arr, obj, item) => { if (!item) { return false } @@ -120,10 +119,6 @@ const users = { store.commit('addNewUsers', mutedUsers) }) - if ('Notification' in window && window.Notification.permission === 'default') { - window.Notification.requestPermission() - } - // Fetch our friends store.rootState.api.backendInteractor.fetchFriends({id: user.id}) .then((friends) => commit('addNewUsers', friends)) diff --git a/src/services/push/push.js b/src/services/push/push.js index 4e4551bf..7d99648a 100644 --- a/src/services/push/push.js +++ b/src/services/push/push.js @@ -26,7 +26,11 @@ function registerServiceWorker () { function askPermission () { return new Promise(function (resolve, reject) { - if (!window.Notification) return resolve('Notifications disabled') + if (!window.Notification) return reject(new Error('Notifications disabled')) + + if (window.Notification.permission !== 'default') { + return resolve(window.Notification.permission) + } const permissionResult = window.Notification.requestPermission(function (result) { resolve(result) @@ -42,6 +46,10 @@ function askPermission () { } function subscribe (registration, store) { + if (!store.rootState.instance.vapidPublicKey) { + return Promise.reject(new Error('VAPID publick key is not found')) + } + const subscribeOptions = { userVisibleOnly: true, applicationServerKey: urlBase64ToUint8Array(store.rootState.instance.vapidPublicKey)