So I have succesfully created a service-worker and recieve a auth token when user enabled notifications permissions, and I confirmed it my Chrome browser.
I recieve the message from POSTman but I get no visible message in my browser, only in console (F12) why?
[firebase-messaging-sw.js] Received background message
firebase-messaging-sw.js:
importScripts('https://www.gstatic.com/firebasejs/10.7.1/firebase-app-compat.js');
importScripts('https://www.gstatic.com/firebasejs/10.7.1/firebase-messaging-compat.js');
const firebaseConfig = {
"placeholder"
};
firebase.initializeApp(firebaseConfig);
const messaging = firebase.messaging();
messaging.onBackgroundMessage((payload) => {
console.log('[firebase-messaging-sw.js] Received background message ', payload);
// Customize notification here
const notificationTitle = payload.data.title;
const notificationOptions = {
body: payload.data.body,
icon: '/firebase-logo.png'
};
self.registration.showNotification(notificationTitle,
notificationOptions);
});
notifications.js:
import { initializeApp } from "https://www.gstatic.com/firebasejs/10.7.1/firebase-app.js";
import { getMessaging, getToken } from "https://www.gstatic.com/firebasejs/10.7.1/firebase-messaging.js";
const firebaseConfig = {
"placeholder"
};
const app = initializeApp(firebaseConfig);
const messaging = getMessaging(app);
var notify = document.getElementById('dropdownMenuButton');
var timeAgoTextElement = document.getElementById('timeAgoText');
async function requestPermissionAndToken() {
if ('serviceWorker' in navigator) {
try {
const registration = await navigator.serviceWorker.register('/firebase-messaging-sw.js');
console.log('Service Worker registered:', registration);
} catch (error) {
console.error('Service Worker registration failed:', error);
}
}
try {
// Request permission for notifications
await Notification.requestPermission();
console.log('Notification permission granted.');
// Retrieve the device token
const token = await getToken(messaging);
getToken(messaging, { vapidKey: ""})
.then((currentToken) => {
if (currentToken) {
console.log('current token for client: ', currentToken);
} else {
console.log('No registration token available. Request permission to generate one.');
}
});
} catch (error) {
console.error('Error requesting permission or obtaining token:', error);
}
}
// Function to mark the notification as clicked and save the current time in cookies
function markNotificationClicked() {
sessionStorage.setItem('notificationClicked', 'true');
sessionStorage.setItem('notificationTime', new Date().toString());
}
// Function to check if the notification has been clicked in the current session using cookies
function isNotificationClicked() {
return sessionStorage.getItem('notificationClicked') === 'true';
}
// Function to update the notification count
function updateNotificationCount() {
var addNumbClass = !isNotificationClicked();
notify.classList.toggle('add-numb', addNumbClass);
}
// Function to format time difference as "just nu," "1 dag sedan," etc.
function formatTimeDifference(timeDiff) {
if (timeDiff < 1) {
return "just nu";
} else if (timeDiff === 1) {
return "1 dag sedan";
} else {
return timeDiff + " dagar sedan";
}
}
// Function to update the time display
function updateTimeAgo() {
var notificationTime = new Date(sessionStorage.getItem('notificationTime')) || new Date();
var now = new Date();
var timeDiff = Math.floor((now - notificationTime) / (1000 * 60 * 60 * 24));
timeAgoTextElement.textContent = formatTimeDifference(timeDiff);
}
// Add an event listener to the dropdown button
notify.addEventListener('click', function() {
notify.setAttribute('data-count', '0');
markNotificationClicked();
updateNotificationCount();
updateTimeAgo(); // Call the function immediately after clicking
// Update the time every hour
setInterval(updateTimeAgo, 1000 * 60 * 60);
});
// Initialize Bootstrap Dropdown
var dropdownElement = document.querySelector('#dropdownMenuButton');
var dropdown = new bootstrap.Dropdown(dropdownElement, {
popperConfig: function(popperConfig) {
popperConfig.modifiers = [
{ name: 'flip', enabled: false, options: { padding: 10 } },
{ name: 'offset', options: { offset: [0, 10] } },
{ name: 'computeStyles', options: { adaptive: false } },
{ name: 'preventOverflow', options: { padding: 10 } }
];
return popperConfig;
}
});
// Update the time immediately
updateTimeAgo();
// Update the notification count initially
updateNotificationCount();
document.addEventListener('DOMContentLoaded', function () {
// Get the checkbox element
const mailCheckbox = document.getElementById('dmNotification');
// Check if the checkbox element exists
if (mailCheckbox) {
// Add a change event listener to the checkbox
mailCheckbox.addEventListener('change', function () {
handleCheckboxChange(mailCheckbox);
});
} else {
console.warn('Checkbox element not found on this page.');
}
});
function handleCheckboxChange(checkbox) {
// Check if notifications are supported by the browser
if ('Notification' in window) {
// Check if the user has granted permission for notifications
if (Notification.permission === 'granted') {
// If the checkbox is checked, show a notification
if (checkbox.checked) {
showNotification('Notification Title', 'Du kommer nu att få aviseringar för privata meddelanden.');
requestPermissionAndToken();
} else {
// If the checkbox is unchecked, show a different notification
showNotification('Notification Title', 'Du har inaktiverat aviseringar för privata meddelanden.');
}
} else {
// If permission is not granted, request permission
Notification.requestPermission().then(function (permission) {
// If permission is granted, show a notification
if (permission === 'granted' && checkbox.checked) {
showNotification('Notification Title', 'Du kommer nu att få aviseringar för privata meddelanden.');
}
});
}
} else {
// Browser does not support notifications
console.error('Notifications not supported in this browser.');
}
}
function showNotification(title, message) {
// Implement your notification logic here
console.log('Notification:', title, message);
}