add checkbox to disable web push

This commit is contained in:
Egor Kislitsyn 2018-12-13 00:03:50 +07:00
parent ee70ec4c7e
commit 02c0e15781
8 changed files with 50 additions and 984 deletions

View file

@ -45,6 +45,7 @@ const settings = {
scopeCopyLocal: user.scopeCopy,
scopeCopyDefault: this.$t('settings.values.' + instance.scopeCopy),
stopGifs: user.stopGifs,
webPushNotificationsLocal: user.webPushNotifications,
loopSilentAvailable:
// Firefox
Object.getOwnPropertyDescriptor(HTMLVideoElement.prototype, 'mozHasAudio') ||
@ -134,6 +135,10 @@ const settings = {
},
stopGifs (value) {
this.$store.dispatch('setOption', { name: 'stopGifs', value })
},
webPushNotificationsLocal (value) {
this.$store.dispatch('setOption', { name: 'webPushNotifications', value })
if (value) this.$store.dispatch('registerPushNotifications')
}
}
}

View file

@ -128,6 +128,18 @@
</li>
</ul>
</div>
<div class="setting-item">
<h2>{{$t('settings.notifications')}}</h2>
<ul class="setting-list">
<li>
<input type="checkbox" id="webPushNotifications" v-model="webPushNotificationsLocal">
<label for="webPushNotifications">
{{$t('settings.enable_web_push_notifications')}}
</label>
</li>
</ul>
</div>
</div>
<div :label="$t('settings.theme')" >

View file

@ -175,7 +175,9 @@
"values": {
"false": "no",
"true": "yes"
}
},
"notifications": "Notifications",
"enable_web_push_notifications": "Enable web push notifications"
},
"timeline": {
"collapse": "Collapse",

View file

@ -1,3 +1,5 @@
import runtime from 'serviceworker-webpack-plugin/lib/runtime'
function urlBase64ToUint8Array (base64String) {
const padding = '='.repeat((4 - base64String.length % 4) % 4)
const base64 = (base64String + padding)
@ -13,7 +15,7 @@ function isPushSupported () {
}
function registerServiceWorker () {
return navigator.serviceWorker.register('/static/sw.js')
return runtime.register()
.catch((err) => console.error('Unable to register service worker.', err))
}

38
src/sw.js Normal file
View file

@ -0,0 +1,38 @@
/* eslint-env serviceworker */
import localForage from 'localforage'
function isEnabled () {
return localForage.getItem('vuex-lz')
.then(data => data.config.webPushNotifications)
}
function getWindowClients () {
return clients.matchAll({ includeUncontrolled: true })
.then((clientList) => clientList.filter(({ type }) => type === 'window'))
}
self.addEventListener('push', (event) => {
if (event.data) {
event.waitUntil(isEnabled().then((isEnabled) => {
return isEnabled && getWindowClients().then((list) => {
const data = event.data.json()
if (list.length === 0) return self.registration.showNotification(data.title, data)
})
}))
}
})
self.addEventListener('notificationclick', (event) => {
event.notification.close()
event.waitUntil(getWindowClients().then((list) => {
for (var i = 0; i < list.length; i++) {
var client = list[i]
if (client.url === '/' && 'focus' in client) { return client.focus() }
}
if (clients.openWindow) return clients.openWindow('/')
}))
})