Skip to content

Instantly share code, notes, and snippets.

@r17x
Last active February 18, 2019 11:14
Show Gist options
  • Select an option

  • Save r17x/3615f8e0e13019e8261cae5e159882f1 to your computer and use it in GitHub Desktop.

Select an option

Save r17x/3615f8e0e13019e8261cae5e159882f1 to your computer and use it in GitHub Desktop.

Prerequire

  • CRA
  • Firebase (Note: Messaging) when i was young

Step by Step

import firebase from 'firebase/app'
import 'firebase/messaging'

const { PUBLIC_URL } = process.env
const initFirebase = () => {
  firebase.initializeApp({
    messagingSenderId: 'YOUR_SENDER_ID',
  })
  navigator.serviceWorker.register(PUBLIC_URL + 'fbm.js').then(registration => {
    firebase.messaging().useServiceWorker(registration)
  })
}

const askForPermissioToReceiveNotifications = async () => {
  try {
    const messaging = firebase.messaging()
    await messaging.requestPermission()
    const token = await messaging.getToken()
    console.log('token: ', token)

    return token
  } catch (error) {
    console.error(error)
  }
}

export { firebase, initFirebase, askForPermissioToReceiveNotifications }
  • create fbm.js on public directory
/* global importScripts */
/* global firebase */
/**
 * firebase messaging
 */
importScripts('https://www.gstatic.com/firebasejs/4.8.1/firebase-app.js')
importScripts('https://www.gstatic.com/firebasejs/4.8.1/firebase-messaging.js')

firebase.initializeApp({
  messagingSenderId: 'YOU_SENDER_ID',
})

const messaging = firebase.messaging()
messaging.setBackgroundMessageHandler(function(payload) {
  console.log(
    '[firebase-messaging-sw.js] Received background message ',
    payload,
  )
  // Customize notification here
  const notificationTitle = 'Background Message Title'
  const notificationOptions = {
    body: 'Background Message body.',
    icon: '/firebase-logo.png',
  }

  return this.registration.showNotification(
    notificationTitle,
    notificationOptions,
  )
})

  • run in index.js
import React from 'react'
import ReactDOM from 'react-dom'
import App from './App'
// import * as SW from './serviceWorker'

import {
  initFirebase,
  askForPermissioToReceiveNotifications,
} from 'utils/push-notification'

ReactDOM.render(
  <>
    <span style={{ display: 'block' }}>
      <button onClick={askForPermissioToReceiveNotifications}>
        Fuck For Permission 🤪
      </button>
    </span>
    <App />
  </>,
  document.getElementById('root'),
)

initFirebase()
// SW.register()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment