-
Notifications
You must be signed in to change notification settings - Fork 108
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Icons and click action in the service worker (#49)
* Icons and click action in the serivice worker. * Update webpush_serviceworker.js * README updated. * Small debugging leftover in the service worker. * Fixed error where multiple notifications would open the same url
- Loading branch information
1 parent
18a7b0e
commit 42d3bf4
Showing
2 changed files
with
42 additions
and
6 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,20 +1,34 @@ | ||
|
||
// Register event listener for the 'push' event. | ||
self.addEventListener('push', function(event) { | ||
// Retrieve the textual payload from event.data (a PushMessageData object). | ||
// Other formats are supported (ArrayBuffer, Blob, JSON), check out the documentation | ||
// on https://developer.mozilla.org/en-US/docs/Web/API/PushMessageData. | ||
var payload = event.data ? event.data.text() : {"head": "No Content", "Body": "No Content"}, | ||
let payload = event.data ? event.data.text() : {"head": "No Content", "body": "No Content", "icon": ""}, | ||
data = JSON.parse(payload), | ||
head = data.head, | ||
body = data.body; | ||
body = data.body, | ||
icon = data.icon; | ||
// If no url was received, it opens the home page of the website that sent the notification | ||
// Whitout this, it would open undefined or the service worker file. | ||
url = data.url ? data.url: self.location.origin; | ||
|
||
// Keep the service worker alive until the notification is created. | ||
event.waitUntil( | ||
// Show a notification with title 'ServiceWorker Cookbook' and use the payload | ||
// as the body. | ||
self.registration.showNotification(head, { | ||
body: body | ||
body: body, | ||
icon: icon, | ||
data: {url: url} | ||
}) | ||
); | ||
}); | ||
}); | ||
|
||
self.addEventListener('notificationclick', function (event) { | ||
event.waitUntil( | ||
event.preventDefault(), | ||
event.notification.close(), | ||
self.clients.openWindow(event.notification.data.url) | ||
); | ||
}) | ||
|