ShakeJ
MNWorld
ShakeJ
전체 방문자
4,222,325
오늘
26
어제
103
  • 카테고리
    • Contact
    • 🤔그냥이야기
    • 📷사진이야기
    • 제주도에서 한달..
    • 옛글
      • 👇Blog
      • 공지사항
      • 이슈
      • 생각들
      • 👇취미
      • 건프라
      • 👇Review
      • 노래리뷰
      • 영화리뷰
      • 👇Travel Story
      • 2011 도쿄여행기
      • 2013 Google IO
      • 2013 Jeju
      • 2014 HONGKONG
      • 2014 Jeju
      • 2014 Sanfransisco
      • 2015 Lombok
      • 2016 HONGKONG
      • 2017 Saigon
      • 국내여행기
      • Photo Story
      • Growth
      • 👇Server
      • Ruby on the Rails
      • Frontend
      • FullStack (MEAN)
      • Ubuntu
      • 👇Android
      • 안드로이드 프로..
      • 번역본
      • 내어플이야기
      • 코드창고
      • 👇iOS
      • 아이폰 프로그래밍
      • 맥북 이야기
      • 👇Microsoft
      • ASP.NET
      • Silverlight
      • 윈도우 이야기
      • 👇IT Story
      • 모바일 이야기
      • 하드웨어 이야기
      • 네트워크 이야기
      • 프로그래밍이야기
      • Database이야기
      • 클라우드이야기
      • 프론트 이야기
      • 마케팅이야기
      • 그래픽 작업
      • 블로그 팁

블로그 메뉴

  • GuestBook

공지사항

인기 글

  • [서울 출사지] 남양주 폐공장과⋯
    2017.03.20
    [서울 출사지] 남양주 폐공장과⋯
  • 소니 노이즈캔슬링 이어폰 MDR-⋯
    2017.03.14
    소니 노이즈캔슬링 이어폰 MDR-⋯
  • 로지텍 M331 무소음 빨간 무선⋯
    2017.04.07
    로지텍 M331 무소음 빨간 무선⋯
  • [Ruby on rails] ElasticSearch⋯
    2017.04.14
    [Ruby on rails] ElasticSearch⋯
  • Rails 구글 크롬 노티피케이션(⋯
    2017.10.13
    Rails 구글 크롬 노티피케이션(⋯

태그

  • 티스토리 초대장
  • 블로그 운영하기
  • 티스토리 팁
  • 블로그 이야기
  • 블로그 꾸미기
  • 블로그 관련
  • D40 사진
  • 블로그 처음
  • 블로그 시작하기
  • 서울 출사지
  • 블로그 초보
  • 블로그 운영
  • 초대장
  • 배너교환
  • 안드로이드 어플 추천
  • shakej
  • iOS 프로그래밍
  • MNWorld
  • 무료배너제작
  • 블로그 잡담
  • 블로그 운영하면서
  • 블로그 만들기
  • 랩
  • 배너무료제작
  • 티스토리
  • 풍경사진
  • 윈도우폰7
  • 배너제작
  • 블로그 팁
  • asp.net

최근 댓글

  • 감사합니다~!
    ShakeJ
  • 포스팅 잘봤습니다 공감 누르고⋯
    hellorly
  • 감사합니다 😄
    ShakeJ
  • 포스팅 잘봐서 좋아요 눌렀어요⋯
    D
  • 앗 옛날에 쓴 그 게임 디스크⋯
    ShakeJ

최근 글

  • [제주도에서 한달을 살아보았다⋯
    2022.06.14
    [제주도에서 한달을 살아보았다⋯
  • [📷사진이야기] 붉은 호치민의⋯
    2022.02.10
    [📷사진이야기] 붉은 호치민의⋯
  • 13년간의 블로그, 오랫만의 글⋯
    2022.02.09
    13년간의 블로그, 오랫만의 글⋯
  • DB의 index와 rails가 기억하는⋯
    2020.10.22
  • 건프라 삼국창걸전 SD를 세울⋯
    2020.09.29
    건프라 삼국창걸전 SD를 세울⋯

티스토리

hELLO · Designed By 정상우.
ShakeJ

MNWorld

Rails 구글 크롬 노티피케이션(푸쉬) FCM(Firebase)로 붙이기
옛글/Ruby on the Rails

Rails 구글 크롬 노티피케이션(푸쉬) FCM(Firebase)로 붙이기

2017. 10. 13. 11:23

Chrome push notification을 기존 GCM이 아닌 FCM으로 붙여보자. 


먼저 클라이언트 쪽 세팅을 해준다. 


1. index.html 


firebase 관련 javascript를 CDN을 통해 import 한다. 


<head>

       <link rel="manifest" href="/js/manifest.json">

</head>

<body>

      <script src="https://www.gstatic.com/firebasejs/4.2.0/firebase-app.js"></script>

      <script src="https://www.gstatic.com/firebasejs/4.2.0/firebase-messaging.js"></script>

      <script src="https://www.gstatic.com/firebasejs/4.2.0/firebase-auth.js"></script>

      <script src="https://www.gstatic.com/firebasejs/4.2.0/firebase.js"></script>

      <script src="/js/firebase_init.js"></script>

      <script src="/js/notification_manager.js"></script>

</body>


2. manifest.json을 추가한다. 


GCM Sender ID는 따로 수정하지 않는다.


{

  "gcm_sender_id": "103953800507",

}


3. firebase_init.js 를 만든다. 


var config = {

  apiKey: "[서버의 API KEY]",

  authDomain: "[콘솔의 프로젝트 이름].firebaseapp.com",

  databaseURL: "https://[콘솔의 프로젝트 이름].firebaseio.com",

  messagingSenderId: "[발신자 ID]",

};

firebase.initializeApp(config);



서버의 API Key 및 발신자 ID 는 firebase console 의 설정 - 클라우드 메시징에서 확인이 가능하다. 


4. notification_manager.js 를 만든다. 


FCM Service worker의 역활을 한다. 토큰을 받아오고, 서버로 토큰을 전송하며, 실제 메세지를 받았을 때에도 웹사이트가 떠 있을 경우 처리한다.


  const messaging = firebase.messaging();


  messaging.onTokenRefresh(function() {

    messaging.getToken()

    .then(function(refreshedToken) {

      console.log('Token refreshed.');

      setTokenSentToServer(false);

      sendTokenToServer(refreshedToken);

      resetUI();

    })

    .catch(function(err) {

      console.log('Unable to retrieve refreshed token ', err);

      showToken('Unable to retrieve refreshed token ', err);

    });

  });


  messaging.onMessage(function(payload) {

    console.log("Message received. ", payload);

    receivedMessage(payload);

  });


  function receivedMessage(payload) {

    alert(payload);

    // TODO : notification이 왔을 때 처리를 도맡아 한다.

  }



  function resetUI() {

    messaging.getToken().then(function(currentToken) {

      if (currentToken) {

        sendTokenToServer(currentToken);

        updateUIForPushEnabled(currentToken);

      } else {

        console.log('No Instance ID token available. Request permission to generate one.');

        updateUIForPushPermissionRequired();

        setTokenSentToServer(false);

      }

    })

    .catch(function(err) {

      console.log('An error occurred while retrieving token. ', err);

      showToken('Error retrieving Instance ID token. ', err);

      setTokenSentToServer(false);

    });

  }


  function sendTokenToServer(currentToken) {

    if (!isTokenSentToServer()) {

      console.log('Sending token to server...' + "\n" + currentToken);

     // TODO : send token to server (실제 서버로 토큰을 전송하자)

      setTokenSentToServer(true);

    } else {

      console.log('Token already sent to server so won\'t send it again ' + 'unless it changes' + "\n" + currentToken);

    }


  }


  function isTokenSentToServer() {

    return window.localStorage.getItem('sentToServer') == 1;

  }


  function setTokenSentToServer(sent) {

    window.localStorage.setItem('sentToServer', sent ? 1 : 0);

  }


  function requestPermission() {

    console.log('Requesting permission...');

    messaging.requestPermission().then(function() {

      console.log('Notification permission granted.');

      resetUI();

    })

    .catch(function(err) {

      console.log('Unable to get permission to notify.', err);

    });

  }


  function deleteToken() {

    messaging.getToken().then(function(currentToken) {

      messaging.deleteToken(currentToken)

      .then(function() {

        console.log('Token deleted.');

        setTokenSentToServer(false);

        resetUI();

      })

      .catch(function(err) {

        console.log('Unable to delete token. ', err);

      });

    })

    .catch(function(err) {

      console.log('Error retrieving Instance ID token. ', err);

      showToken('Error retrieving Instance ID token. ', err);

    });


  }


  function updateUIForPushEnabled(currentToken) {


  }


  function updateUIForPushPermissionRequired() {

  Notification.requestPermission();

  }


  resetUI();



5. firebase-message-sw.js 를 만들어 상위 폴더에 넣어준다 (/public)


웹사이트가 떠 있지 않을 때 (브라우져상에서 없을 때 처리)



importScripts('https://www.gstatic.com/firebasejs/4.2.0/firebase-app.js');

importScripts('https://www.gstatic.com/firebasejs/4.2.0/firebase-messaging.js');

importScripts('/js/firebase_init.js');


const messaging = firebase.messaging();


messaging.setBackgroundMessageHandler(function(payload) {

  console.log('[firebase-messaging-sw.js] Received background message ', payload);

});


해당 웹사이트를 돌리면, 콘솔에 token이 찍히게 된다. 

예를 들어 "czKLLl66-Hg:APA91bEZEVhjp-LiYTaIV_8yZ-HLf0Gq3bQ2dj4BbD-9PMbqApXhinGDEnVWvp8ZGFsMEx1s9jWEQXL0Dpdg76E-en954lEGGn6edxugmTN0yl3AhS-5pzaivKOYEc9Uy4MoehqXBepA" 

서버쪽에서 해당 토큰(registration_id)로 FCM을 Sending 한다.


서버쪽 세팅을 한다.


1. 'FCM' Gem 을 추가한다. 


Gemfile

gem 'fcm'


2. 특정 모델에 class method로 테스트 코드를 추가해보자. 


def self.send_notification

    fcm = FCM.new("[서버 API 키]")

    registration_ids= ["[콘솔에서 찍혔던 client의 token]"]

    options = {data: {score: "123"}, collapse_key: "updated_score"}

    response = fcm.send(registration_ids, options)

  end


3. 콘솔에서 해당 메소드를 실행시켜보자. 



콘솔에서 Message 와 payload를 받은 것이 확인된다.

저작자표시비영리변경금지
  • 카카오스토리
  • 트위터
  • 페이스북

'옛글 > Ruby on the Rails' 카테고리의 다른 글

Rails upgrade 5.2 to 6.0  (0) 2019.05.24
Mac Postgres install and command  (0) 2019.03.27
Rails 구글 크롬 노티피케이션(푸쉬) FCM(Firebase)로 붙이기  (0) 2017.10.13
[Ruby on rails] ElasticSearch 를 붙여보자  (0) 2017.04.14
[Ruby on rails] Sidekiq이 버벅거린다면, Rails sidekiq process 갯수 늘리기  (0) 2017.04.13
[Ruby on rails] 서버 속도 (+MYSQL)를 개선해보자!  (0) 2017.04.12
    추천글👇
    • [📷사진이야기] 붉은 호치민의 노을
    Chrom push notification, Chrome push, Push, 구글 크롬 노티피케이션 보내기, 크롬 FCM 푸쉬
    ShakeJ
    ShakeJ
    댓글쓰기
    다음 글
    Mac Postgres install and command
    이전 글
    [Ruby on rails] ElasticSearch 를 붙여보자
    • 이전
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • ···
    • 17
    • 다음

    티스토리툴바