// https://firebase.google.com/docs/web/learn-more?hl=ja#libraries-cdn import {initializeApp} from 'https://www.gstatic.com/firebasejs/10.4.0/firebase-app.js'; import {getMessaging, getToken} from 'https://www.gstatic.com/firebasejs/10.4.0/firebase-messaging.js'; const apiUrl = 'https://api.cloud-messenger.net'; const scriptConfig = {}; const getConfig = function() { const scripts = document.getElementsByTagName('script'); for (const script of scripts) { if (!script.src.match(/\/push_notification.js/)) continue; for (const key in script.dataset) { if (['siteid', 'uuid', 'customkey'].includes(key)) scriptConfig[key] = script.dataset[key]; } } }; const registerSw = async function(serviceWorkerPath) { const workerPath = serviceWorkerPath ? serviceWorkerPath : '/firebase-messaging-sw.js'; if ('serviceWorker' in navigator) { localStorage.setItem('cloudMessengerSiteId', scriptConfig.siteid); return await navigator.serviceWorker.register(workerPath) .then(function(registration) { console.log('firebase-messaging-sw.js registration successful'); return registration; }, function(err) { console.log('firebase-messaging-sw.js registration failed: ', err); }); }; }; const getPushToken = async function(result, messaging, isRetry) { await getToken(messaging, { vapidKey: result.webPushCertificate, }).then((currentToken) => { const res = $.ajax({ type: 'post', url: `${apiUrl}/push/${scriptConfig.siteid}/token`, data: JSON.stringify({token: currentToken, uuid: scriptConfig.uuid, customKey: scriptConfig.customkey}), contentType: 'application/json', dataType: 'json', async: false, }); sessionStorage.setItem('cloudMessengerTokenId', res.responseJSON.tokenId); }).catch((err) => { if (!isRetry && err.message.match(/Subscription failed - no active Service Worker/)) { console.log('Wait retry get push token...'); setTimeout(() => getPushToken(result, messaging, true), 3000); return; } throw new Error(err); }); }; const initFirebase = function(result, swRegistration) { const app = initializeApp(result.firebaseConfig); const messaging = getMessaging(app); messaging.swRegistration = swRegistration; Notification.requestPermission().then((permission) => { if (permission === 'granted') { // 通知を許可した場合 getPushToken(result, messaging); } else { // 通知を拒否した場合 console.log('Unable to get permission to notify.'); } }); }; const loadFirebaseConfig = function() { $.ajax({ type: 'get', url: `${apiUrl}/push/${scriptConfig.siteid}/config`, }).then((data) => { if (data.firebaseConfig) { (async () => { const swRegistration = await registerSw(data.serviceWorkerPath); initFirebase(data, swRegistration); })(); } else { throw new Error('firebaseConfig not found.'); } }); }; $('#closeCloudMessengerPopup').on('click', function() { $('#cloudMessenger').remove(); }); const iPhonePushTokenRequest = async function() { const res = await $.ajax({ type: 'get', url: `${apiUrl}/push/${scriptConfig.siteid}/config`, }); if (res.firebaseConfig) { const app = initializeApp(res.firebaseConfig); const messaging = getMessaging(app); await getPushToken(res, messaging); } else { throw new Error('firebaseConfig not found.'); } }; const enableCart = async function() { const tokenId = sessionStorage.getItem('cloudMessengerTokenId'); await $.ajax({ type: 'post', url: `${apiUrl}/cart_push/${scriptConfig.siteid}`, data: JSON.stringify({tokenId: tokenId}), contentType: 'application/json', dataType: 'json', async: false, }); }; const disableCart = async function() { const tokenId = sessionStorage.getItem('cloudMessengerTokenId'); await $.ajax({ type: 'delete', url: `${apiUrl}/cart_push/${scriptConfig.siteid}`, data: JSON.stringify({tokenId: tokenId}), contentType: 'application/json', dataType: 'json', async: false, }); }; $(function() { if (location.protocol != 'https:') { throw new Error('This service is only available on https protocol.'); } getConfig(); loadFirebaseConfig(); }); window.cloudMessenger = { iPhonePushTokenRequest: iPhonePushTokenRequest, enableCart: enableCart, disableCart: disableCart, };