Add action buttons to web push notifications
Currently action buttons are displayed only by Chrome. Chrome displays at most 2 buttons per notification.
You can include action buttons inside your web push notifications. In this way, a notification can have multiple links or actions.
When you send a web push notification you can add any number of action buttons. Each action button has the following fields:
- Title: the label displayed to the user for the action button.
- Link (optional): the page that opens up when the user clicks the button. If you leave it blank, the main link of the notification will be used.
- Icon (optional): the URL of a small icon for the action button. An alternative to icons is to include emoticons or other symbols inside the title.
- Action (optional): an ID for the action that can be used to trigger a Javascript callback. If a Javascript action with that ID is defined, it will be executed. Otherwise the action ID will be ignored and the link will be used instead.
Usually when you create an action button you set a link that will be opened in a new window when the button is clicked. However developers can also define custom Javascript actions that are executed in background. For example you may define a button called "Like" that saves the reaction of the user in background without opening a window.
In order to bind a Javascript function to a button, you first need to define the function inside your service worker:
service-worker.js
self.notificationActions = {
// Your custom actions must be defined here
exampleAction: function (customData) {
console.log('exampleAction called with data: ' + customData);
// You can use the notification "custom data" field to pass a param to your actions
var itemId = customData;
// All actions must return a Promise
return fetch('/item/' + itemId + '/like', { method: "POST" });
}
};
The actions must be defined as properties of the self.notificationActions
object. Then, when you send a notification, you can bind an action to a button by entering the name of that action in the Action field.
You can pass an argument to your action by entering a value for the Custom data field when you send the notification.
Note that all actions must return a Promise.