Ich versuche, einen Chats-Abschnitt auf meiner ASP .NET Core MVC-Website zu erstellen, und ich habe Probleme beim Laden der Firebase-Dienste und des Firebase-Messaging-sw.js und vieles mehr. Gibt es eine Dokumentation, die ich befolgen kann, da ich keine Informationen darüber finde, wie ich dies in ASP .NET Core MVC speziell erreichen kann.
@model List
@using Market.Services.Chats
@inject IChatsService _chatsService
@using Microsoft.AspNetCore.Mvc.Localization
@inject IViewLocalizer Localizer
@{
ViewData["Title"] = Localizer["PageTitle"];
}
@foreach(ContactViewModel contact in Model)
{
}
@Localizer["Send"]
@section Scripts {
// Import the functions you need from the SDKs you need
import { initializeApp } from "https://www.gstatic.com/firebasejs/11.5.0/firebase-app.js";
import { getAnalytics } from "https://www.gstatic.com/firebasejs/11.5.0/firebase-analytics.js";
import { getMessaging, getToken, onMessage } from "https://www.gstatic.com/firebasejs/11.5.0/firebase-messaging.js";
// Your web app's Firebase configuration
const firebaseConfig = {
Imagine this is filled in
};
// Initialize Firebase
const app = initializeApp(firebaseConfig);
const analytics = getAnalytics(app);
const messaging = getMessaging(app);
// Register Service Worker before requesting FCM token
navigator.serviceWorker.register('/firebase-messaging-sw.js')
.then((registration) => {
messaging.useServiceWorker(registration);
console.log("Service Worker registered successfully:", registration);
// Request permission for notifications and pass the registration object
Notification.requestPermission().then((permission) => {
if (permission === "granted") {
console.log("Notification permission granted.");
requestFcmToken(registration); // Pass the registration object
}
});
})
.catch((error) => {
console.error("Service Worker registration failed:", error);
});
// Get the device token
function requestFcmToken(registration) {
getToken(messaging, {
vapidKey: "MY_VAPID_KEY",
serviceWorkerRegistration: registration
}).then((currentToken) => {
if (currentToken) {
console.log("Device Token:", currentToken);
// Send token to the server
fetch('/Chats/RegisterDeviceToken', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ token: currentToken })
});
}
}).catch((err) => {
console.log("Error getting token:", err);
});
}
// Handle incoming messages
onMessage(messaging, (payload) => {
console.log("Message received: ", payload);
new Notification(payload.notification.title, {
body: payload.notification.body,
icon: payload.notification.icon
});
});
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,
Body: input.value,
RecipientId: selectedContact.id,
Type: "message"
};
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.");
}
});
}
< /code>
FireBase Messaging Service Worker < /p>
// Import the Firebase messaging service worker script
importScripts('https://www.gstatic.com/firebasejs/11.5.0/firebase-messaging.js');
// Initialize Firebase in the service worker context
const firebaseConfig = {
apiKey: "AIzaSyCtHqk0vkhh7t86AHsgHzHq-uzGybTLPo0",
authDomain: "market-229ca.firebaseapp.com",
projectId: "market-229ca",
storageBucket: "market-229ca.appspot.com",
messagingSenderId: "847650161276",
appId: "1:847650161276:web:e83938a265b8accf437ff9",
measurementId: "G-JQ6RXKT7M9"
};
// Initialize Firebase messaging
firebase.initializeApp(firebaseConfig);
// Get an instance of Firebase Messaging to handle background messages
const messaging = firebase.messaging();
// Handle background messages
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
};
// Show a notification
self.registration.showNotification(notificationTitle, notificationOptions);
});
Fehler Ich begegne:
Index: 189 Registrierung von Service Worker Fehlgeschlagen: TypeError: Versäumt, einen Serviceworker für Scope ('https: // Localhost: 44354/') mit Skript zu registrieren (Script ('https: // localhost: 44354/Firebase-Messaging-sw.js'): Serviceworkerin-Skriptbewertung fehlgeschlagen
Ich versuche, einen Chats-Abschnitt auf meiner ASP .NET Core MVC-Website zu erstellen, und [url=viewtopic.php?t=18848]ich habe Probleme[/url] beim Laden der Firebase-Dienste und des Firebase-Messaging-sw.js und vieles mehr. Gibt es eine Dokumentation, die ich befolgen kann, da ich keine Informationen darüber finde, wie ich dies in ASP .NET Core MVC speziell erreichen kann.[code] @model List @using Market.Services.Chats @inject IChatsService _chatsService @using Microsoft.AspNetCore.Mvc.Localization @inject IViewLocalizer Localizer
@{ ViewData["Title"] = Localizer["PageTitle"]; }
@foreach(ContactViewModel contact in Model) {
}
@Localizer["Send"]
@section Scripts {
// Import the functions you need from the SDKs you need import { initializeApp } from "https://www.gstatic.com/firebasejs/11.5.0/firebase-app.js"; import { getAnalytics } from "https://www.gstatic.com/firebasejs/11.5.0/firebase-analytics.js"; import { getMessaging, getToken, onMessage } from "https://www.gstatic.com/firebasejs/11.5.0/firebase-messaging.js";
// Your web app's Firebase configuration const firebaseConfig = { Imagine this is filled in };
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);
//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; }
// Show a notification self.registration.showNotification(notificationTitle, notificationOptions); });
[/code] Fehler Ich begegne:
Index: 189 Registrierung von Service Worker Fehlgeschlagen: TypeError: Versäumt, einen Serviceworker für Scope ('https: // Localhost: 44354/') mit Skript zu registrieren (Script ('https: // localhost: 44354/Firebase-Messaging-sw.js'): Serviceworkerin-Skriptbewertung fehlgeschlagen
Ich implementieren Push-Benachrichtigungen mit einem Bild in meiner iOS-App mithilfe von Firebase Cloud Messaging (FCM). Ich habe eine benutzerdefinierte NotificationServiceExtension erstellt, um das...
Ich untersuche, warum es keine Tonbenachrichtigung gibt, wenn eine Push -Benachrichtigung über unsere App gesendet wird. Benachrichtigungen funktionieren, aber es gibt keinen Ton (noch Vibration),...
Ich untersuche, warum es keine Tonbenachrichtigung gibt, wenn eine Push -Benachrichtigung über unsere App gesendet wird. Benachrichtigungen funktionieren, aber es gibt keinen Ton (noch Vibration),...
Ich versuche, meine Flutter -App für iOS zu erstellen, und der Prozess fällt aufgrund eines Cocoapods -Abhängigkeitskonflikts mit GoogleUtilities/Umgebung fehl. Es scheint, dass verschiedene...
Ich versuche, Push-Benachrichtigungen auf iOS und Android mit Firebase/mesaging einzurichten.
Ich habe den Einrichtungsteil mit googleservice-info usw. befolgt ...
Ich habe die Push-Benachrichtigung...