main.js
// src/main.js
import Vue from 'vue'
import App from './App.vue'
import './registerServiceWorker'
import router from './router'
import store from './store'
import vuetify from './plugins/vuetify'
import { getMessaging, onMessage } from "firebase/messaging";
Vue.config.productionTip = false
new Vue({
router,
store,
vuetify,
render: h => h(App),
created() {
// Set up Firebase auth state change listener
const { dispatch } = this.$store;
// Initialize Firebase authentication to check for the logged-in user
dispatch('auth/initializeAuth');
dispatch('auth/fetchUsers');
dispatch('mylogs/fetchMylogs');
if ('serviceWorker' in navigator) {
navigator.serviceWorker.register('/firebase-messaging-sw.js')
.then((registration) => {
console.log('Service Worker registered with scope:', registration.scope);
})
.catch((err) => {
console.error('Service Worker registration failed:', err);
});
}
// Request Notification Permission
// '알림 요청'으로 fcm 토큰을 저장할 것이므로 웹앱을 시작할 때 알림 표시 요청과 관게없이 onMessage를 구현해 둔다.
const messaging = getMessaging();
// Handle incoming messages in the foreground
onMessage(messaging, (payload) => {
console.log('Message received: ', payload);
// Extract notification data
const title = payload.notification.title;
const options = {
body: payload.notification.body,
icon: payload.notification.icon || "/img/push-noti-icon.png",
badge: "/img/push-badge-icon.png",
image: "/img/push-image.png",
data: { url: payload.notification.click_action || 'https://velog.io/@inetsos/posts' } // Custom data for the click event
};
// Show notification
const notification = new Notification(title, options);
// Handle click event on the notification
notification.onclick = (event) => {
event.preventDefault(); // Prevent the browser from focusing the Notification's tab
window.open(notification.data.url, '_blank'); // Open the URL in a new tab
};
});
}
}).$mount('#app')