Move service worker registration to when the page loads

This commit is contained in:
Tanner Collin 2016-12-30 07:20:55 +00:00
parent 431c7beb38
commit 35efefc13e

View File

@ -9,6 +9,8 @@ export default class NotifPage extends React.Component {
super(props); super(props);
this.state = { this.state = {
supported: false,
registration: null,
haveperm: false, haveperm: false,
connected: false, connected: false,
socket: io.connect() socket: io.connect()
@ -40,7 +42,6 @@ export default class NotifPage extends React.Component {
socket.on('message', (data) => { socket.on('message', (data) => {
console.log("Notification: " + data); console.log("Notification: " + data);
this.checkperm(Notification.permission);
this.sendNotification(data); this.sendNotification(data);
}); });
} }
@ -55,14 +56,11 @@ export default class NotifPage extends React.Component {
vibrate: [200, 100, 200] vibrate: [200, 100, 200]
}; };
try { if (this.state.registration) {
navigator.serviceWorker.register('/js/sw.js').then((reg) => { console.log(this.state.registration.showNotification(title, options));
reg.showNotification(title, options); } else {
}); console.log(new Notification(title, options));
} catch (e) { // If we are on a browser without serviceWorker
new Notification(title, options);
} }
} }
checksupport() { checksupport() {
@ -72,6 +70,14 @@ export default class NotifPage extends React.Component {
if (supported) { if (supported) {
Notification.requestPermission(permission => { Notification.requestPermission(permission => {
this.checkperm(permission); this.checkperm(permission);
try {
navigator.serviceWorker.register('/js/sw.js').then((reg) => {
this.setState({registration: reg});
});
} catch (e) { // If we are on a browser without serviceWorker
this.setState({registration: false});
}
}.bind(this)); }.bind(this));
} }
} }