Chrome extension with Firebase Cloud Messaging API: Defualt notification on msedge

295 Views Asked by At

I have programmed an Chrome Extension with Manifest Version 3, and it works very well in chrome with no problems. I use Firebase Cloud Messaging API V1 to get messages from my server to clients. However the problem is that when i use the extensions in MS Edge it pops up with the default notification as well as my custom one in the push event.

So my question is how do i get it to work in edge without it sending the "This site has been updated in the background" and my custom one at the same time. Rather i want only my custom notification to be shown.

I have tried doing research online as to how i can resolve the issue, however that does not seem to be much information on the web directly related to ms edge and only chrome instead.

manifest.json:

{
    "name": "Staines Memorial College Notifications",
    "version": "1.0.1",
    "description": "Recieve notifications for Staines Memorial College and the Diary App.",
    "manifest_version": 3,
    "author": "Braydan Mengel - Staines Memorial College",
    "action": {
        "default_popup": "Ext_Status.html",
        "default_title": "Staines Memorial College Notifications Extension"
    },
    "permissions": [
        "notifications",
        "background",
        "storage"
    ],
    "background": {
        "service_worker": "background.js",
        "type": "module"
    },
    "icons": {
        "48": "Images/ExtensionIcon48.png",
        "128": "Images/ExtensionIcon128.png"
    }
}

background.js:

import { getMessaging } from "./firebase/firebase-messaging-sw.js";
import { getToken } from "./firebase/firebase-messaging.js";
import { initializeApp } from "./firebase/firebase-app.js";

//init firebase
initializeApp({
    apiKey: "",
    authDomain: "",
    projectId: "",
    storageBucket: "",
    messagingSenderId: "",
    appId: "",
    measurementId: ""
});

//global variables
var UserID;

//chrome local storage
chrome.storage.local.get(["userData"]).then((result) => {
    if (result.userData === undefined) {
        chrome.tabs.create({ url: chrome.runtime.getURL("Ext_Login.html") });
    } else {
        UserID = result.userData.uuid;
        setTimeout(() => {
            RegTopic();
        }, 1000)
    }
});

async function RegTopic() {
    //get the gcm device token and send it to the server
    const token = await getToken(getMessaging(), {
        serviceWorkerRegistration: self.registration
    });

    const details = {
        "userid": UserID,
        "token": token
    };

    fetch("https://example.com/ins/tokens/fcm/regToken", {
        method: "POST",
        headers: {
            "Content-Type": "application/json; charset=UTF-8"
        },
        body: JSON.stringify(details)
    })
        .then(response => response.json())
        .then(data => {
            if (data.message === 'Registered') {
                console.log('Registered token successfully!');
            }
        })
        .catch(error => {
            setTimeout(() => {
                RegTopic();
            }, 5000)
            console.error("Error:", error);
        });
}

//when a message is received
self.addEventListener('push', function (event) {
    const Message = event.data.json();

    if (Message.data.link === "NONE") {
        // No link found
        if (Message.data.priority === "0") {
            // Priority is set to 0 meaning Normal
            const showNotification = self.registration.showNotification(`Staines Notifications - ${Message.data.title}`, {
                icon: "../Images/Notify.png",
                body: Message.data.body,
                requireInteraction: false,
                data: {
                    notificationid: Message.data.notificationid,
                    linkOpening: Message.data.link
                }
            });

            event.waitUntil(showNotification);
        } else if (Message.priority === "1") {
            // Priority is set to 1 meaning Important
            const showNotification = self.registration.showNotification(`Staines Notifications - ${Message.data.title}`, {
                icon: "../Images/Notify.png",
                body: Message.data.body,
                requireInteraction: true,
                data: {
                    notificationid: Message.data.notificationid,
                    linkOpening: Message.data.link
                }
            });

            event.waitUntil(showNotification);
        }
    } else {
        // Link is included; priority is set to 1 meaning Important by default
        const showNotification = self.registration.showNotification(`Staines Notifications - ${Message.data.title}`, {
            icon: "../Images/Notify.png",
            body: Message.data.body,
            requireInteraction: true,
            data: {
                notificationid: Message.data.notificationid,
                linkOpening: Message.data.link
            }
        });

        event.waitUntil(showNotification);
    }
});

//Login message handler
chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
    if (message.type === 'login') {
        UserID = message.data.userid;
        const response = { status: 'success' };
        sendResponse(response);

        RegTopic();
    }
});

// Notification handlers
self.addEventListener('notificationclick', function (event) {
    const clickedNotification = event.notification;
    const linkOpening = clickedNotification.data.linkOpening;

    if (linkOpening !== 'NONE') {
        event.waitUntil(
            clients.openWindow(linkOpening)
        );
    }
});

self.addEventListener('notificationclose', function (event) {
    const clickedNotification = event.notification;
    const linkOpening = clickedNotification.data.linkOpening;

    if (linkOpening !== 'NONE') {
        event.waitUntil(
            clients.openWindow(linkOpening)
        );
    }
});

Note that i use version 9.0.0 of firebase-app.js, firebase-messaging.js, and firebase-messaging-sw.js. These files are packaged with the extension.

Here is the directory tree if you need it: file tree source

0

There are 0 best solutions below