- importScripts не найден в сервис-воркере firebase-messaging-sw.js, я считаю это необходимым.
- Регистрация сервис-воркера в файле site.js не работает. li>
Мне приходится использовать CDN, потому что импорт пакетов Firebase в JS обычно не работает - Даже когда я импортировал и настроил все, что мог не получить Firebase Токен
- site.js файл в wwwroot/site.js:
window.addEventListener('load', () => {
navigator.serviceWorker.register('/firebase-messaging-sw.js')
.then(registration => {
console.log('ServiceWorker registration successful with scope: ', registration.scope);
})
.catch(error => {
console.log('ServiceWorker registration failed:', error);
});
});
}
- Просмотр чатов:
@using Market.Services.Chats
@inject IChatsService _chatsService
@{
ViewData["Title"] = "Chats";
}
@foreach(ContactViewModel contact in Model)
{
}
Send
import { initializeApp } from 'https://www.gstatic.com/firebasejs/11.1 ... ase-app.js';
import { getMessaging, getToken, onMessage } from 'https://www.gstatic.com/firebasejs/11.1 ... ssaging.js';
// TODO: Add SDKs for Firebase products that you want to use
// https://firebase.google.com/docs/web/se ... -libraries
// Your web app's Firebase configuration
// For Firebase JS SDK v7.20.0 and later, measurementId is optional
const firebaseConfig = {};
// Initialize Firebase
const app = initializeApp(firebaseConfig);
const messaging = getMessaging(app);
// Request permission to receive notifications
Notification.requestPermission().then((permission) => {
if (permission === "granted") {
console.log("Notification permission granted.");
// Get the FCM token
getToken(messaging).then((currentToken) => {
if (currentToken) {
console.log("FCM Token:", currentToken);
// You can send this token to your server for later use
} else {
console.log("No registration token available. Request permission to generate one.");
}
}).catch((err) => {
console.log("An error occurred while retrieving the token. ", err);
});
} else {
console.log("Notification permission denied.");
}
});
// Handle incoming messages (foreground)
onMessage(messaging, (payload) => {
console.log("Message received: ", payload);
});
// Handle background messages
//messaging.onBackgroundMessage((payload) => {});
let contactsData = @Html.Raw(Json.Serialize(Model));
let contacts = document.getElementsByClassName("contact-container");
let info = document.getElementById("chat-contact-info-container");
let infoEmail = document.getElementById("info-email");
let infoName = document.getElementById("info-name");
let infoPicture = document.getElementById("info-picture");
let selected = null;
Array.from(contacts).forEach(contact => {
contact.addEventListener("click", function () {
let attribute = contact.getAttribute("data-id");
info.classList.remove("hidden");
if (selected != attribute) {
selected = attribute;
// Find the selected contact using JavaScript
let selectedContact = contactsData.find(c => c.id == selected);
if (selectedContact) {
//Load profile picture
// Display the selected contact details
infoEmail.innerHTML = selectedContact.email;
infoName.innerHTML = `${selectedContact.firstName} ${selectedContact.lastName}`;
infoPicture.src = selectedContact.profilePictureURL;
console.log("Selected contact:", selectedContact);
}
}
});
});
//Sending message logic
let input = document.getElementById("chat-form-input");
let button = document.getElementById("chat-form-button");
button.addEventListener("click", async (e) => {
//Send message using service
e.preventDefault();
let selectedContact = contactsData.find(c => c.id == selected);
// Validate input
if (!input.value || !selectedContact || !selectedContact.deviceToken) {
alert("Please select a contact and enter a message.");
return;
}
const payload = {
DeviceToken: selectedContact.deviceToken, // Replace with actual token
Title: "New Message",
Body: input.value,
Id: selectedContact.id, // Replace with actual contact ID
Status: "unread" // Example status
};
console.log(payload);
try {
const response = await fetch("/Chats/Send", {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify(payload)
});
if (response.ok) {
const result = await response.json();
console.log(result.message);
alert("Message sent successfully.");
input.value = ""; // Clear the input field
} else {
console.error("Failed to send message.");
alert("Failed to send message. Please try again.");
}
} catch (error) {
console.error("Error sending message:", error);
alert("An error occurred while sending the message.");
}
});
- firebase-messaging-sw.js в wwwroot/firebase-messaging-sw.js:
importScripts('https://www.gstatic.com/firebasejs/11.1 ... -compat.js');
// Initialize Firebase
const firebaseConfig = {};
const messaging = firebase.messaging();
// Background message handler (commented out for now)
messaging.onBackgroundMessage(function (payload) {
console.log("Received background message ", payload);
const notificationTitle = payload.notification.title;
const notificationOptions = {
body: payload.notification.body,
icon: payload.notification.icon,
};
self.registration.showNotification(notificationTitle, notificationOptions);
});
Весь проект можно найти здесь:
https://github.com/gabigoranov/farmers- ... rketPortal
Вот некоторые сообщения об ошибках:
at firebase-messaging-sw.js:1:1
(anonymous) @ firebase-messaging-sw.js:1
firebaseNamespaceCore.ts:102 Uncaught FirebaseError: Firebase: No Firebase App '[DEFAULT]' has been created - call Firebase App.initializeApp() (app-compat/no-app).
at o (firebaseNamespaceCore.ts:102:27)
at Object.e [as messaging] (firebaseNamespaceCore.ts:153:31)
at firebase-messaging-sw.js:15:28
o @ firebaseNamespaceCore.ts:102
e @ firebaseNamespaceCore.ts:153
(anonymous) @ firebase-messaging-sw.js:15
site.js?v=Gz2QdXTfmz6XOA5S_mrhCuSqTb0qZ6sGhNiF7niNstk:8 ServiceWorker registration failed: TypeError: Failed to register a ServiceWorker for scope ('https://localhost:44354/') with script ('https://localhost:44354/firebase-messaging-sw.js'): ServiceWorker script evaluation failed```
Подробнее здесь: https://stackoverflow.com/questions/793 ... t-core-mvc
Мобильная версия