Можно ли получить FCM в .NET Core MVC?C#

Место общения программистов C#
Ответить
Anonymous
 Можно ли получить FCM в .NET Core MVC?

Сообщение Anonymous »

Я хочу реализовать чаты в своем приложении .NET Core MVC, и я успешно реализовал отправку сообщений с помощью пакета FirebaseAdmin, однако при попытке настроить получение сообщений с помощью JS возникает несколько проблем.
  • Я не могу использовать importScripts в сервисном работнике firebase-messaging-sw.js, я думаю, это необходимо.
  • Регистрация работник службы в файл site.js не работает.
  • Мне приходится использовать CDN, потому что импорт пакетов Firebase в JS обычно не работает
  • Даже когда я все импортировал и настроил, я не могу получить токен Firebase
Вот часть моего кода:

Код: Выделить всё

if ('serviceWorker' in navigator && 'PushManager' in window) {
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);
});
});
}
  • Просмотр чатов:

Код: Выделить всё

@model List
@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.0/firebase-app.js';
import { getMessaging, getToken, onMessage } from 'https://www.gstatic.com/firebasejs/11.1.0/firebase-messaging.js';
// TODO: Add SDKs for Firebase products that you want to use
// https://firebase.google.com/docs/web/setup#available-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.");
}

});



Код: Выделить всё

importScripts('https://www.gstatic.com/firebasejs/11.1.0/firebase-app-compat.js');
importScripts('https://www.gstatic.com/firebasejs/11.1.0/firebase-messaging-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


Подробнее здесь: https://stackoverflow.com/questions/793 ... t-core-mvc
Ответить

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

Вернуться в «C#»