export function initializeMessaging(dispatch) { const messaging = firebase.messaging() if (!publicVapidKey) { /* eslint-disable no-console */ console.warn( 'Skipping messaging initialization, publicVapidKey not set in src/config.js' ) /* eslint-enable no-console */ return } messaging.usePublicVapidKey(publicVapidKey) // Handle Instance ID token updates messaging.onTokenRefresh(() => { getTokenAndWriteToProfile() }) // Handle incoming messages. Called when: // - a message is received while the app has focus // - the user clicks on an app notification created by a service worker // `messaging.setBackgroundMessageHandler` handler. messaging.onMessage(payload => { const DEFAULT_MESSAGE = 'Message!' // Dispatch showSuccess action messageActions.showSuccess( get(payload, 'notification.body', DEFAULT_MESSAGE) )(dispatch) }) // Request permission to setup browser notifications requestPermission() }
/** * Gets all topics user has subscribed for * * @returns Promise<Array<String>> */ getSubscriptions() { const messaging = firebase.messaging(); return messaging.getToken() .then(token => { if (!token) { return Promise.resolve([]); } const url = TOPICS_ENDPOINT + '?token=' + token; return fetch(url, { headers: { Accept: 'application/json' } }); }) .then(response => { return response.json(); }) .then(json => { return json.subscriptions; }) .catch(err => { console.error('Error fetching subscriptions: ', err); return Promise.resolve([]); }); }
/** * Get messaging token from Firebase messaging */ function getMessagingToken() { return firebase .messaging() .getToken() .catch(err => { console.error('Unable to retrieve refreshed token ', err) // eslint-disable-line no-console return Promise.reject(err) }) }
export function requestPermission() { return firebase .messaging() .requestPermission() .then(getTokenAndWriteToProfile) .catch(err => { console.error('Unable to get permission to notify: ', err) // eslint-disable-line no-console return Promise.reject(err) }) }
isNotificationBlocked() { const messaging = firebase.messaging(); return messaging.getToken() .then(_ => { return false; }) .catch(err => { if (err.code === ERROR_NOTIFICATIONS_BLOCKED) { return true; } return Promise.reject(err); }); }
/** * Disables Notifications from a topic. * * @param topic - The topic to unsubscribe from. * @returns Promise */ unsubscribe(topic) { console.log('Unsubscribing from: ' + topic); const messaging = firebase.messaging(); return messaging.getToken() .then(token => { const url = UNSUBSCRIBE_ENDPOINT + '/' + topic; return this._postWithToken(url, token); }).catch(err => { if (this._checkBlockedNotification(err)) { err.blocked = true; } return Promise.reject(err); }); }