-
Firebase Web topic 구독프로그래밍/Javascript 2020. 10. 15. 12:37반응형
Firebase 앱 푸쉬 테스트 예제는 많은데 웹 푸쉬 테스트 예제는 없어서 삽집을 많이 하게 됐다..
topic 구독은 예제가 더 없더라,,
그래서 해보고 테스트 예제를 남긴다.
https://github.com/firebase/quickstart-js
firebase에서 제공하는 기본 소스를 다운로드받아 Message폴더 안에있는 소스를 실행
Visual Studio Code를 사용하여 폴더를 열어주고
Live Server를 마켓플레이스에서 설치하여 실행하면
오류가 무자비 하게 뜬다. 이제 이 오류를 해결하고 Topic을 설정해줄 예정인데
firebase-message-sw.js를 보면
importScripts('/__/firebase/7.23.0/firebase-app.js');importScripts('/__/firebase/7.23.0/firebase-messaging.js');importScripts('/__/firebase/init.js');이런 import가 있는데 __가 뭔지를 모르겠으니 일단 싹다 지워줬다.
그리고 바로 사진에 있는 주석처리 된 부분을 풀어주고
firebase의 프로젝트에 들어가보면 자신의
Firebase SDK snippet에 올바른 주소로 변경해준다.
importScripts('https://www.gstatic.com/firebasejs/7.23.0/firebase-app.js');importScripts('https://www.gstatic.com/firebasejs/7.23.0/firebase-messaging.js');// Initialize the Firebase app in the service worker by passing in// your app's Firebase config object.// https://firebase.google.com/docs/web/setup#config-objectfirebase.initializeApp({apiKey: 'api-key',authDomain: 'project-id.firebaseapp.com',databaseURL: 'https://project-id.firebaseio.com',projectId: 'project-id',storageBucket: 'project-id.appspot.com',messagingSenderId: 'sender-id',appId: 'app-id',measurementId: 'G-measurement-id',});이 부분도 같이 복사해서 붙혀넣어주자.
그리고 실행시켜보면
역시 오류가 뜬다.
그래도 오류 하난 사라져있다.
html 소스를 들어가보면
이와같은 소스를 발견 할 수 있는데 물론 오류가 발생한다.
이 부분을 해결 해주기 위해 올바른 스크립트를 가져 올수 있게 변경해줘야한다.
html 소스를 보면 마찬가지로
이런 소스가 있는데 이를 경로를 제대로 고쳐주고 init.js는 지워주자
초기화해주기 위해서 사용하는 것 같은데 이건 그냥 sdk에서 실행해주면 된다.
init을 지웠으니 init을 대신 할 html에 소스를 적어주기 위해 sdk를 그대로 복사해서
<script>
var firebaseConfig = {
apiKey: "xxxxxxxxxxxxxx",
authDomain: "xxxxxxxxxxxxx",
databaseURL: "xxxxxxxxxxx",
projectId: "xxxxxxxxxxx",
storageBucket: "xxxxxxxxx",
messagingSenderId: "xxxxxxxxx",
appId: "xxxxxxxxxxxxx",
measurementId: "xxxxxxxxxx"
};
// Initialize Firebase
firebase.initializeApp(firebaseConfig);
</script>
로 넣어준다.
그러면 또 이런 잡다한 오류가 발생하는데
맨위에 messaging has ~~~ 오류는 두번 등록되어서 그런거니
js에서 맨위 소스코드를 const messaging = firebase.messaging(); 을 지워준다.
// Import and configure the Firebase SDK// These scripts are made available when the app is served or deployed on Firebase Hosting// If you do not serve/host your project using Firebase Hosting see https://firebase.google.com/docs/web/setupconst messaging = firebase.messaging();messaging.usePublicVapidKey('<YOUR_PUBLIC_VAPID_KEY_HERE>');html 소스를 보면 위에 <YOUR_PUBLIC_VAPID_KEY_HERE>을 지우고
Firebase 클라우드메시지에서 웹 푸시 인증서 키를 입력해준다.
그리고 실행하면
오류없이 잘 나오는 것을 볼 수 있다.
이제 topic을 등록해줘야 한다.
https://stackoverflow.com/questions/40389335/how-to-subscribe-to-topics-with-web-browser-using-firebase-cloud-messaging
에 나와 있는 소스를 사용해주면 된다.
function subscribeTokenToTopic(token, topic) {fetch('https://iid.googleapis.com/iid/v1/'+token+'/rel/topics/'+topic, {method: 'POST',headers: new Headers({'Authorization': 'key='+fcm_server_key})}).then(response => {if (response.status < 200 || response.status >= 400) {throw 'Error subscribing to topic: '+response.status + ' - ' + response.text();}console.log('Subscribed to "'+topic+'"');}).catch(error => {console.error(error);})}function Topic(Token){subscribeTokenToTopic(Token, "토픽이름을 적어주세요.");}4번째 줄에 보면 fcm_server_key를 바꿔줘야하는데 이는 클라우드 메시지에 토큰값을 String형식인 ('key='+"XXXXXXXX")처럼 넣어주고
Topic 함수에서 정할 토픽이름을 적어주자
그럼 이제 Topic 함수를 사용해서 토큰값을 전달해줘야하니
function resetUI() {clearMessages();showToken('loading...');// [START get_token]// Get Instance ID token. Initially this makes a network call, once retrieved// subsequent calls to getToken will return from cache.messaging.getToken().then((currentToken) => {if (currentToken) {sendTokenToServer(currentToken);updateUIForPushEnabled(currentToken);} else {// Show permission request.console.log('No Instance ID token available. Request permission to generate one.');// Show permission UI.updateUIForPushPermissionRequired();setTokenSentToServer(false);}}).catch((err) => {console.log('An error occurred while retrieving token. ', err);showToken('Error retrieving Instance ID token. ', err);setTokenSentToServer(false);});// [END get_token]}if (currentToken){
에 Token(currentToken);을 사용해주면
된다.
if (currentToken) {sendTokenToServer(currentToken);updateUIForPushEnabled(currentToken);Topic(currentToken);.
그럼 Topic 구독도 완료된다.
구독 테스트는 firebase에서 할 수 있다.
번외로
공식 웹 홈페이지를 가서 보면
https://firebase.google.com/docs/cloud-messaging/js/topic-messaging?hl=ko#node.js
// These registration tokens come from the client FCM SDKs.
var registrationTokens = [
'YOUR_REGISTRATION_TOKEN_1',
// ...
'YOUR_REGISTRATION_TOKEN_n'
];
// Subscribe the devices corresponding to the registration tokens to the
// topic.
admin.messaging().subscribeToTopic(registrationTokens, topic)
.then(function(response) {
// See the MessagingTopicManagementResponse reference documentation
// for the contents of response.
console.log('Successfully subscribed to topic:', response);
})
.catch(function(error) {
console.log('Error subscribing to topic:', error);
});위 글을 볼 수 있는데
admin을 사용하지 않아서 이 소스를 사용하지 않았다.
반응형'프로그래밍 > Javascript' 카테고리의 다른 글
onclick="" 사용시, 페이지 리로딩되는 현상 (0) 2019.09.16 An invalid XML character (Unicode: 0x3) was found in the CDATA section. 에러 발생시 (0) 2019.09.05 ajax로 multipart/form-data 사용하기 (0) 2019.08.14