$(function() { if ('serviceWorker' in navigator && 'PushManager' in window) { // Firebase初期化 firebase.initializeApp(firebaseConfig); // Firebase Messagingオブジェクトを取得します。 const messaging = firebase.messaging(); //コンソールから生成された公開鍵を追加 messaging.usePublicVapidKey(firebasePublicVapidKey); function registToken(token) { $.ajax({ 'url': 'https://hitachiastemo.shapplix.com/core_sys/inc/push/php/token_set.php' ,'cache': false ,'type': 'POST' ,'data': {'token': token} ,'error': function(XMLHttpRequest, textStatus, errorThrown) { alert('Your session may have been disconnected. Please try to log in again.'); console.log('setRequest error[XMLHttpRequest:'+XMLHttpRequest.status+'][textStatus:'+textStatus+'][errorThrown:'+errorThrown.message+']'); } , beforeSend: function(xhr){ xhr.overrideMimeType("text/html;charset=UTF-8"); } ,'success': function(data) { if(data.result==1) { $('#push-receive-btn-area').show(); $('#push-receive-btn').removeClass('is-disable').addClass('push-receiving').text('Turn off push notifications.'); fmcSubscribe('granted'); } else { alert('Failed to set notification. Please set your browser’s notification settings back to "Confirm" and try again.'); console.log(data.result); } isClicked = false; } ,'dataType':'json' }); } var isClicked = false; var nowToken = null; function setTokenToServer(token) { console.log(token); if(nowToken == token) { return; } else if(nowToken != null) { // 自システム(Appサーバー)から旧token削除など $.ajax({ 'url': 'https://hitachiastemo.shapplix.com/core_sys/inc/push/php/token_del.php' ,'cache': false ,'type': 'POST' ,'data': {'token': nowToken} ,'error': function(XMLHttpRequest, textStatus, errorThrown) { alert('Your session may have been disconnected. Please try to log in again.'); console.log('delRequest error[XMLHttpRequest:'+XMLHttpRequest.status+'][textStatus:'+textStatus+'][errorThrown:'+errorThrown.message+']'); } , beforeSend: function(xhr){ xhr.overrideMimeType("text/html;charset=UTF-8"); } ,'success': function(data) { if(data.result==1) { registToken(token); } else { alert('Server Error2'); console.log(data.result); isClicked = false; } } ,'dataType':'json' }); } else { $('.disp-token').text(token); fmcSubscribe('granted'); nowToken = token; registToken(token); } } function delTokenFromServer() { if(nowToken) { // 自システム(Appサーバー)からtoken削除など $.ajax({ 'url': 'https://hitachiastemo.shapplix.com/core_sys/inc/push/php/token_del.php' ,'cache': false ,'type': 'POST' ,'data': {'token': nowToken} ,'error': function(XMLHttpRequest, textStatus, errorThrown) { alert('Your session may have been disconnected. Please try to log in again.'); console.log('delRequest error[XMLHttpRequest:'+XMLHttpRequest.status+'][textStatus:'+textStatus+'][errorThrown:'+errorThrown.message+']'); } , beforeSend: function(xhr){ xhr.overrideMimeType("text/html;charset=UTF-8"); } ,'success': function(data) { if(data.result==1) { } else { alert('Server Error3'); console.log(data.result); } isClicked = false; } ,'dataType':'json' }); messaging.deleteToken(nowToken); nowToken = null; } fmcSubscribe('default'); $('#push-receive-btn-area').show(); $('#push-receive-btn').removeClass('is-disable push-receiving').text('PUSH通知を受け取る設定にする'); isClicked = false; } var isSend = false; function checkPermissionpermission(permission) { if(!isSend) { isSend = true; switch (permission) { case 'granted': // 許可された場合、トークン取得 messaging.getToken() .then(function(currentToken) { if(currentToken) { setTokenToServer(currentToken); fmcSubscribe('granted'); } else { $('#fmcsub').removeClass('granted').addClass('denied').removeClass('default') console.log('There are no instance ID tokens available. Request permission to generate.'); } isSend = false; }) .catch(function(err) { console.log('An error occurred while retrieving the token.', err); isSend = false; }); break; case 'denied': // ブロックされた場合 $('#push-receive-btn-area').show(); $('#push-receive-btn').removeClass('is-disable push-receiving').text('Set to receive push notifications.'); fmcSubscribe('denied'); alert('Notifications are blocked in your browser settings. Please change the setting.'); isSend = false; break; case 'default': // 無視された場合 default: $('#push-receive-btn-area').show(); $('#push-receive-btn').removeClass('is-disable push-receiving').text('Set to receive push notifications.'); isSend = false; fmcSubscribe('default'); break; } } } // サービスワーカーの登録 navigator.serviceWorker.register('https://hitachiastemo.shapplix.com/core_sys/inc/push/js/sw.js').then(function(registration) { // サービスワーカー登録成功 console.log('Successful Service Worker Registration scope: ', registration.scope); // サービスワーカーを指定 messaging.useServiceWorker(registration); //トークンが更新された通知 messaging.onTokenRefresh(function() { console.log('You have been notified of a token update.'); this.messaging.getToken().then(function(refreshedToken) { setTokenToServer(refreshedToken); }).catch(function(err) { console.log('An error occurred while retrieving the updated token.', err); }); }); //ブラウザ起動時の受信。SWでは設定できない。 messaging.onMessage(function(payload) { console.log('onMessage:Message received. ', payload); var options = { //body: payload.data.body body: payload.notification.body ,icon: 'https://hitachiastemo.shapplix.com/core_sys/inc/push/images/icon-192x192.png' }; //if(payload.fcmOptions && payload.fcmOptions.link) { if(payload.notification.click_action!='') { //options['data'] = payload.fcmOptions && payload.fcmOptions.link; options['data'] = payload.notification.click_action; } //registration.showNotification(payload.data.title, options); registration.showNotification(payload.notification.title, options); }); //現在の通知状態チェック switch (Notification.permission) { case 'granted': // 許可された場合、自システム(Appサーバー)のtoken登録状況チェック messaging.getToken().then(function(currentToken) { if(currentToken) { $.ajax({ 'url': 'https://hitachiastemo.shapplix.com/core_sys/inc/push/php/token_check.php' ,'cache': false ,'type': 'POST' ,'data': {'token': currentToken} ,'error': function(XMLHttpRequest, textStatus, errorThrown) { alert('Your session may have been disconnected. Please try to log in again.'); console.log('checkRequest error[XMLHttpRequest:'+XMLHttpRequest.status+'][textStatus:'+textStatus+'][errorThrown:'+errorThrown.message+']'); } , beforeSend: function(xhr){ xhr.overrideMimeType("text/html;charset=UTF-8"); } ,'success': function(data) { if(data.result==1) { nowToken = currentToken; $('#push-receive-btn').addClass('push-receiving').text('Turn off push notifications.'); fmcSubscribe('granted'); } else { $('#push-receive-btn').removeClass('push-receiving').text('Set to receive push notifications.'); fmcSubscribe('default'); } $('#push-receive-btn').removeClass('is-disable'); $('#push-receive-btn-area').show(); } ,'dataType':'json' }); } else { console.log('There are no instance ID tokens available. Request permission to generate.'); } }) .catch(function(err) { console.log('An error occurred while retrieving the token.', err); }); break; case 'denied': // ブロックされた場合 fmcSubscribe('denied'); break; case 'default': // 無視された場合 default: fmcSubscribe('default'); $('#push-receive-btn-area').show(); $('#push-receive-btn').removeClass('is-disable push-receiving').text('Set to receive push notifications.'); break; } $('#push-receive-btn').on('click', function() { if(!isClicked) { isClicked = true; if($('#push-receive-btn').hasClass('push-receiving')) { if(window.confirm('Do you want to stop receiving notifications?')) { $('#push-receive-btn').addClass('is-disable'); delTokenFromServer(); } else { isClicked = false; } } else { if(window.confirm('Do you want to receive notifications?')) { $('#push-receive-btn').addClass('is-disable'); // messaging.requestPermission() は非推奨 //ブラウザの通知設定チェック Notification.requestPermission().then(function(permission) { checkPermissionpermission(permission); isClicked = false; }); } else { isClicked = false; } } } return false; }); }).catch(function(err) { // サービスワーカー登録失敗 console.log('ServiceWorker registration failure: ', err); }); } else { console.log('Push is not available.'); fmcSubscribe('disable'); } function fmcSubscribe(result){ console.log(result); if(result == 'granted'){ $('#fmcsub').addClass('granted').removeClass('denied').removeClass('default'); $('#fmctxt').text('Notification is enabled'); }else if(result == 'denied'){ $('#fmcsub').removeClass('granted').addClass('denied').removeClass('default'); $('#fmctxt').text('Notification is blocked'); }else if(result == 'default'){ $('#fmcsub').removeClass('granted').removeClass('denied').addClass('default'); $('#fmctxt').text('Notification is disabled'); }else if(result == 'disallow'){ $('#fmcsub').removeClass('granted').addClass('denied').removeClass('default'); $('#fmctxt').text('Notification is not available in your browser'); }else if(result == 'disable'){ $('#fmcsub').removeClass('granted').addClass('denied').removeClass('default'); $('#fmctxt').text('Notifications are not available'); } } });