self.addEventListener('push', function(event) {
console.log('Received a push message', event);
var icon = 'https://en.m.wikipedia.org/static/apple-touch/wikipedia.png';
var tag = 'wikipedia-reader-notification';
var d = new Date();
var month = [ 'January', 'February', 'March', 'April', 'May', 'June',
'July', 'August', 'October', 'November', 'December' ][ d.getMonth() ];
var pageTitle = 'Wikipedia:Today\'s_featured_article/' + month + '_' + d.getDate() + ',_' + d.getFullYear();
var origin = location.protocol + '//' + location.hostname;
var qs = 'action=query&prop=extracts&format=json&formatversion=2&explaintext=&titles=' + pageTitle;
var headers = new Headers();
var request = new Request( '/w/api.php?' + qs, {
method: 'GET',
headers: headers,
mode: 'cors',
cache: 'default'
} );
fetch( request ).then( function ( resp ) {
if (resp.status !== 200) {
throw new Error();
}
resp.json().then( function ( data ) {
var page,
pages = data.query.pages;
if ( pages.length ) {
page = pages[0];
// wait until promise gets fulfilled
event.waitUntil(
self.registration.showNotification( page.title, {
body: page.extract,
icon: icon,
tag: tag
})
);
}
} );
} );
});
self.addEventListener('notificationclick', function(event) {
console.log('On notification click: ', event.notification.tag);
// Android doesn’t close the notification when you click on it
// See: http://crbug.com/463146
event.notification.close();
// This looks to see if the current is already open and
// focuses if it is
event.waitUntil(clients.matchAll({
type: "window"
}).then(function(clientList) {
for (var i = 0; i < clientList.length; i++) {
var client = clientList[i];
if (client.url == '/' && 'focus' in client)
return client.focus();
}
if (clients.openWindow)
return clients.openWindow('/');
}));
});