본문 바로가기
웹 개발 이야기/js, jquery

[JS] Firebase Web Push

by Gommin 2023. 6. 14.

웹푸시.zip
0.00MB

if ('serviceWorker' in navigator) {
  window.addEventListener('load', () => {
    navigator.serviceWorker.register('/firebase-messaging-sw.js');
  });
}

var firebaseConfig = {
  apiKey: "firebase apiKey",
  authDomain: "firebase Domain",
  databaseURL: "firebase url",
  projectId: "dmonster-mine",
  storageBucket: "dmonster-mine.appspot.com",
  messagingSenderId: "273700180185",
  appId: "1:273700180185:web:fc3f9ca5870abc7f846ec8",
  measurementId: "G-HFB7T3GQZ3"
};


firebase.initializeApp(firebaseConfig);
const messaging=firebase.messaging();

function IntitalizeFireBaseMessaging() {
    messaging
        .requestPermission()
        .then(function () {
            console.log("Notification Permission");
            return messaging.getToken();
        })
        .then(function (token) {
            console.log("Token : "+token);
            if((token != '' || token != null) && ses_mt_id != ''){
              //ajax쳐서 로그인상태라면 token을 DB에 저장
              $.post("./web_fcm_token_update.php", {mt_id : ses_mt_id, fcm_token: token}, function(data){

        	    });
            }
            // document.getElementById("token").innerHTML=token;
        })
        .catch(function (reason) {
            console.log(reason);
        });
}

messaging.onMessage(function (payload) {
    console.log(payload);
    const notificationOption={
        body:payload.notification.body,
    };
    //
    if(Notification.permission==="granted"){
        // var notification=new Notification(payload.notification.title,notificationOption);
        //
        // notification.onclick=function (ev) {
        //     ev.preventDefault();
        //     window.open(payload.notification.click_action,'_blank');
        //     notification.close();
        // }
        if(payload.data.type == 'reserve'){
          $('#modal1_link_btn').attr("href", "./sub_reserve_info.php?idx="+payload.data.link);
          $('#modal1').modal();
        }else if(payload.data.type == 'chat'){
          if(chat_sub_link == '/sub/online_chat_list.php'){
            push_on_chatting_room(payload.data.link, 'chat_detail');
          }else if(chat_sub_link == '/sub/program_chat_list.php'){
            push_on_chatting_room(payload.data.link, 'chat_detail');
          }else{
            if(payload.data.type2 == 'reserve'){
              $('#modal2_link_btn').attr("href", "./online_chat_list.php?idx="+payload.data.link);
            }else if(payload.data.type2 == 'program'){
              $('#modal2_link_btn').attr("href", "./program_chat_list.php?idx="+payload.data.link);
            }

            $('#modal2').modal();
          }
        }
    }
});
messaging.onTokenRefresh(function () {
    messaging.getToken()
      .then(function (newtoken) {
          console.log("New Token : "+ newtoken);
      })
      .catch(function (reason) {
          console.log(reason);
      })
})
IntitalizeFireBaseMessaging();

1. 경로 제일 상단에 "firebase-messaging-sw.js"를 셋팅한다.
내용은 firebase웹 푸시 셋팅값으로 데이터를 변경한다.

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

var firebaseConfig = {
  apiKey: "firebase apiKey",
  authDomain: "firebase Domain",
  databaseURL: "firebase url",
  projectId: "dmonster-mine",
  storageBucket: "dmonster-mine.appspot.com",
  messagingSenderId: "273700180185",
  appId: "1:273700180185:web:fc3f9ca5870abc7f846ec8",
  measurementId: "G-HFB7T3GQZ3"
};

firebase.initializeApp(firebaseConfig);

const messaging = firebase.messaging();

messaging.setBackgroundMessageHandler(function (payload){
  // console.log(payload);
  const notification=JSON.parse(payload);
  const notificationOption={
      body:"새로운 예약이 추가되었습니다",
      icon:notification.icon
  };
  return self.registration.showNotification("MINE 알림",notificationOption);
});

 

2. 웹푸시가 실행되어야할 head에 아래 내용을 추가한다.
"defer"는 필수

<head>
<!-- firebase -->
<script defer type="module" src="https://www.gstatic.com/firebasejs/8.10.1/firebase-app.js"></script>
<script defer type="module" src="https://www.gstatic.com/firebasejs/8.10.1/firebase-messaging.js"></script>


<!--server side-->
<script defer src="./firebase-run.js"></script>

</head>

 

3. head와 동일한 폴더내에 "firebase-run.js"를 추가한다.

 

댓글