最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

c# - Receiving Firebase Cloud Messaging Notifications in ASP .NET Core MVC - Stack Overflow

programmeradmin7浏览0评论

I am trying to create a chats section in my asp core mvc website and I am having issues with loading the firebase services and firebase-messaging-sw.js and a lot more. Is there a documentation I can follow since I am not finding information on how I can achieve this in ASP .Net core mvc specifically.

This is my Chats.cshtml


@model List<ContactViewModel>
@using Market.Services.Chats
@inject IChatsService _chatsService
@using Microsoft.AspNetCore.Mvc.Localization
@inject IViewLocalizer Localizer

@{
    ViewData["Title"] = Localizer["PageTitle"];
}

<section class="chats-section">
    <div class="contacts-container">
        @foreach(ContactViewModel contact in Model)
        {
            <partial name="_ContactPartial" model="contact" />
        }
    </div>

    <div class="chat-container">
        <div id="chat-contact-info-container" class="hidden">
            <h2 id="info-email"></h2>
            <div class="row">
                <h1 id="info-name"></h1>
                <div class="contact-profile-picture">
                    <img id="info-picture" alt="contact-picture" />
                </div>
            </div>
        </div>

        <form class="chat-form">
            <input class="chat-input" id="chat-form-input" placeholder="Type here..."/>
            <button class="chat-button" id="chat-form-button" type="submit">@Localizer["Send"]</button>
        </form>
    </div>
</section>
@section Scripts {
    <script type="module">
        // Import the functions you need from the SDKs you need
        import { initializeApp } from ".5.0/firebase-app.js";
        import { getAnalytics } from ".5.0/firebase-analytics.js";
        import { getMessaging, getToken, onMessage } from ".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
            });
        });
    </script>


    <script>
        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.");
            }

        });

    </script>

}

Firebase messaging service worker


// Import the Firebase messaging service worker script
importScripts('.5.0/firebase-messaging.js');

// Initialize Firebase in the service worker context
const firebaseConfig = {
    apiKey: "AIzaSyCtHqk0vkhh7t86AHsgHzHq-uzGybTLPo0",
    authDomain: "market-229ca.firebaseapp",
    projectId: "market-229ca",
    storageBucket: "market-229ca.appspot",
    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);
});


Errors I am encountering:

Index:189 Service Worker 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

发布评论

评论列表(0)

  1. 暂无评论