Friday 28 January 2022

FCM Notification On Android Not Opening Chrome When Tapped

So I am developing a website for a company. I need to send a notification from server to all supervisors account (whether on browser or mobile). So I implement the FCM for sending the notification.

In the client web page I have these code to make the client subscribe to FCM:

var firebaseConfig = {
    messagingSenderId: "xxxx",
    apiKey: "xxxx",
    projectId: "xxxx",
    appId: "xxxxx"
};
firebase.initializeApp(firebaseConfig);

const messaging = firebase.messaging();
messaging
    .requestPermission()
    .then(function () {
        console.log('Notification permission granted.');

        // get the token in the form of promise
        return messaging.getToken();
    })
    .then(async function (token) {
        console.log('Token: ' + token);
        await fetch("/api/Supervisor/SubscribeToAllTopic?token=" + token);
    })
    .catch(function (err) {
        console.log('Unable to get permission to notify.', err);
    });

let enableForegroundNotification = true;
messaging.onMessage(function (payload) {
    console.log('Message received. ', payload);

    if (enableForegroundNotification) {
        let notification = payload.notification;

        const notificationOptions = {
            body: notification.body,
            data: payload.data
        };

        navigator.serviceWorker
            .getRegistrations()
            .then((registration) => {
                //registration[0].showNotification(notification.title);
                registration[0].showNotification(notification.title, notificationOptions);
            });
    }
});

Then there is service worker firebase-messaging-sw.js to handle the background activities:

importScripts("https://www.gstatic.com/firebasejs/7.16.1/firebase-app.js");
importScripts(
    "https://www.gstatic.com/firebasejs/7.16.1/firebase-messaging.js",
);
// For an optimal experience using Cloud Messaging, also add the Firebase SDK for Analytics.
importScripts(
    "https://www.gstatic.com/firebasejs/7.16.1/firebase-analytics.js",
);

// Initialize the Firebase app in the service worker by passing in the
// messagingSenderId.
firebase.initializeApp({
    messagingSenderId: "xxxx",
    apiKey: "xxxx",
    projectId: "xxxx",
    appId: "xxxx"
});

// Retrieve an instance of Firebase Messaging so that it can handle background
// messages.
const messaging = firebase.messaging();

messaging.setBackgroundMessageHandler(function (payload) {
    console.log(
        "[firebase-messaging-sw.js] Received background message ",
        payload,
    );
    // Customize notification here
    const notificationTitle = payload.notification.title;
    const notificationOptions = {
        body: payload.notification.body,
        data: payload.data
    };

    return self.registration.showNotification(
        notificationTitle,
        notificationOptions,
    );
});

self.addEventListener('notificationclick', function (event) {
    console.log(event);
    event.notification.close();
    //var urlToRedirect = event.notification.data.action;
    //event.waitUntil(self.clients.openWindow(urlToRedirect));

    let url = event.notification.data.action;
    event.notification.close(); // Android needs explicit close.
    event.waitUntil(
        clients.matchAll({ type: 'window' }).then(windowClients => {
            // Check if there is already a window/tab open with the target URL
            for (var i = 0; i < windowClients.length; i++) {
                var client = windowClients[i];
                // If so, just focus it.
                if (client.url === url && 'focus' in client) {
                    return client.focus();
                }
            }
            // If not, then open the target URL in a new window/tab.
            if (clients.openWindow) {
                return clients.openWindow(url);
            }
        })
    );


});

The notifications are successfully sent to web browsers or mobile phones. The problem is when I tapped the notification, it supposed to open chrome and redirect me to the action url. This only works if only there is an open web browser with the same host url.

For example if my website is https://mywebsite.com, if the mobile phone is now browsing at that url, it will open a new window and redirect to the action url (it works fine). If I do not have the host url opened, then tapping the notification will do nothing, also if the mobile phone does not have a chrome instance running, tapping the notification will do nothing.

How can I always instruct the client to open chrome and redirect them to the action url?



from FCM Notification On Android Not Opening Chrome When Tapped

No comments:

Post a Comment