DEV Community

Kevin Naidoo
Kevin Naidoo

Posted on

FCM browser push notifications - open a different URL on click.

Let me save you an hour or two trying to find information in Google's sea of documentation which can be painful.

Here's a little Python script, you can use to send Push notifications in the background. This allows for users to be directed to a URL on your website, instead of just landing on your homepage.

import argparse
import json
import requests
import google.auth.transport.requests
from google.oauth2 import service_account

# Get this from your project settings in the firebase console.
PROJECT_ID = "project-name-messaging"
API_BASE_URL = "https://fcm.googleapis.com/"
SCOPES = ["https://www.googleapis.com/auth/firebase.messaging"]

'''
Get authentication token. 
To get a credentials JSON file - you will need to:

1) In firebase messaging - click on "Service Accounts"
2) Manage service account permissions
3) On the right hand side you will see the 3 vertical dots
 next to your service account name. Click on "Manage Keys"
4) Add Key. And Download the .json file.
'''
credentials = service_account.Credentials.from_service_account_file(
    "app-credentials-file.json", scopes=SCOPES
)
request = google.auth.transport.requests.Request()
credentials.refresh(request)
token = credentials.token

headers = {
    "Authorization": f"Bearer {token}",
    "Content-Type": "application/json; UTF-8",
}


'''
Build message payload. Notice the "webpush" options. 
We set "link" - this will override the default
link opened - which basically is your root domain. 
Here you can change that to any sub-link on your domain.
'''
fcm_message = {
    "message": {
        "token": "YOUR DEVICE TOKEN",
        "notification": {
            "title": "Some crazy sale",
            "body": "Hurry big sale...",
            "image": "http://mywebsite.com/someimg.png",
        },
        "webpush": {
            "fcmOptions": {
                "link": "http://mywebsite.com/some/page/10",
            }
        },
    }
}

resp = requests.post(
    f'{API_BASE_URL}v1/projects/{PROJECT_ID}/messages:send',
    data=json.dumps(fcm_message),
    headers=headers,
)

print(resp.text)

Enter fullscreen mode Exit fullscreen mode

Conclusion

That's all there is to it. You can also add various other options to your payload for mobile devices and extra parameters.

Here's the full documentation for the Message payload:
https://developers.google.com/gmail/api/reference/rest/v1/users.messages#Message

You will still need to implement the JavaScript code for receiving messages and registering service workers on your website.

Here are some samples on GitHub from the Firebase team to help you implement the JavaScript aspects: https://github.com/firebase/quickstart-js/tree/master/messaging

Top comments (0)