4

I'm sending fcm message to the web application, I'm able to receive the message in background but when I click on alert, it does not open the URL in browser, everything is working fine its just the link that is not working.

Here is the message I'm sending, please help

{
"notification": {
"title": "Hello World",
"body": "Enjoy your coffee"
},

 "webpush": {

      "fcm_options": {
        "link": "https://weather.com/en-CA/weather/today/l/CAON4756:"
      }
    }

"to" : ""
}

My firebase-messaging-sw.js file

importScripts('https://www.gstatic.com/firebasejs/6.3.4/firebase-app.js');
importScripts('https://www.gstatic.com/firebasejs/6.3.4/firebase-messaging.js');



firebase.initializeApp({
  'messagingSenderId': ''
});

const messaging = firebase.messaging();




  • I found this post, it helps but still not sure why fcm_options link url is not working https://stackoverflow.com/questions/57380133/fcm-link-not-working-in-desktop-notification – anshul mahajan Sep 19 '19 at 19:19

1 Answers1

4

Only the link which has the same host with the registered service worker could be opened.

In your message, the host is weather.com which senses not the host of your registered service worker.

My solution to open a third party site is setting url param.

Solution

javascript in somepage

let urlToOpen = getQueryVariable(window.location.search.substring(1), "url")
if (urlToOpen) {
    window.open(urlToOpen, "_self")
}

function getQueryVariable(query, variable) {
    const vars = query.split("&")
    for (let i = 0; i < vars.length; i++) {
        const pair = vars[i].split("=")
        if (pair[0] === variable) {
            return pair[1]
        }
    }
    return false
}

message to send, just replace the "url2somepage" with a url to somepage(the host is the same to service worker)

{
    "notification": {
        "title": "Hello World",
            "body": "Enjoy your coffee"
    },

    "webpush": {
        "fcm_options": {
            "link": "url2somepage" + "?url=" + "https://weather.com/en-CA/weather/today/l/CAON4756:"
            // replace the 'url2somepage' with the url to a page which contains the previous js
        }
    }

    "to" : ""
}
A1lo
  • 51
  • 1
  • 6
  • 1
    The point that the `Only the link which has the same host with the registered service worker could be opened.` was the key. Thanks. But it still doesn't route to the Correct page in the link if the tab is open. If I close the tab. It works. – Saras Arya May 15 '21 at 11:36