define([ 'jquery', 'underscore', 'Mirasvit_PushNotification/js/debugger', 'Mirasvit_PushNotification/js/lib/firebase', 'Mirasvit_PushNotification/js/deps'//prevent error: Cannot read property '*' of undefined ], function ($, _, debug) { 'use strict'; return { token: null, messaging: null, isPermissionDenied: false, isSupported: true, isSafari: false, initialize: function () { if (this.isSafariBrowser()) { this.isSupported = false; debug.info("Safari browser is not supported"); return; } firebase.initializeApp({ messagingSenderId: PN_SENDER_ID }); if ('Notification' in window) { debug.info("Browser is supported"); } else { debug.error("Browser is not supported"); this.isSupported = false; return; } this.messaging = firebase.messaging(); this.messaging.getToken() .then(function (token) { debug.info("Obtained token: " + token); this.subscriptionUpdate(token); }.bind(this)) .catch(function (err) { debug.error(err); this.isPermissionDenied = true; }.bind(this)); var scope = location.protocol + '//' + location.hostname + (location.port ? ':' + location.port : '') + '/firebase-cloud-messaging-push-scope'; this.messaging.onMessage(function (payload) { debug.info(payload); navigator.serviceWorker.getRegistration(scope) .then(function (registration) { var data = payload.data; var id = data.tag; fetch(location.origin + '/push_notification/action/track?fb=0&event=fetch&id=' + id); var notification = data; notification.data = data; if (registration) { return registration.showNotification(notification.title, notification); } else { navigator.serviceWorker.register('/firebase-messaging-sw.js'); Notification.requestPermission(function (result) { if (result === 'granted') { navigator.serviceWorker.ready.then(function (registration) { return registration.showNotification(notification.title, notification); }); } }); } }); }); }, subscribe: function () { debug.info("Request permission..."); this.messaging.requestPermission() .then(function () { debug.info("accepted"); this.messaging.getToken() .then(function (token) { debug.info("Token: " + token); this.subscriptionUpdate(token); }.bind(this)) .catch(function (err) { debug.error(err); }); }.bind(this)) .catch(function (err) { debug.error(err); if (Notification.permission === 'denied') { this.isPermissionDenied = true; } }.bind(this)); }, subscriptionUpdate: function (token) { debug.info("Update subscription"); if (!this.token) { this.token = token; this.ensureSubscription(); } }, ensureSubscription: function () { debug.info('Ensure subscription'); $.ajax(window.PN_SUBSCRIBE_URL, { method: 'post', data: { token: this.token } }); }, isSafariBrowser: function() { let chromeAgent = navigator.userAgent.indexOf("Chrome") > -1; let safariAgent = navigator.userAgent.indexOf("Safari") > -1; this.isSafari = safariAgent && !chromeAgent; return this.isSafari; } }; });