iT邦幫忙

2

Firebase WEB推播 Safari 無效果

請問 可以使用firebase在iOS(版本是13)的Safari發送推播嗎?
目前做到可以用電腦Chrome與Android發送推播(使用firebase),
但是網頁在Safari上無任何反應(連Token都沒有)

主網頁部分

<head>
  <meta charset="utf-8">
  <title>MyFirebaseFirstApp</title>
  <base href="">

  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="icon" type="image/x-icon" href="favicon.ico">

  <link rel="manifest" href="manifest.json">

</head>


  <script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
	<script src="https://www.gstatic.com/firebasejs/4.6.1/firebase-app.js"></script>
	<script src="https://www.gstatic.com/firebasejs/4.6.1/firebase-messaging.js"></script>

<script>

  var messaging = null;

	$(document).ready(function () {

		// Firebase 專案設定
		  var firebaseConfig = {
		    apiKey: "AIzaSyDgu1aSqfLX-LIPabasyXZKOpkntu1zZ8c",
		    authDomain: "eatfood-b38e7.firebaseapp.com",
		    databaseURL: "https://eatfood-b38e7.firebaseio.com",
		    projectId: "eatfood-b38e7",
		    storageBucket: "eatfood-b38e7.appspot.com",
		    messagingSenderId: "143139701423",
		    appId: "1:143139701423:web:ba1fbd55e8b55e55a34a5a",
		    measurementId: "G-GQ27ZK9QBW"
		  };

	  // 初始firebase
	  	firebase.initializeApp(firebaseConfig);

   // 指定 firebase-messaging-sw.js 的路徑與本 html 檔相同
	   navigator.serviceWorker.register('firebase-messaging-sw.js')
	    .then((registration) => {
	     messaging.useServiceWorker(registration);
	   });

		// 啟動 Firebase Messaging
	    messaging = firebase.messaging();

		// 收到訊息時的處理(前景)
	    messaging.onMessage(function (payload) {

	  		console.log('onMessage run');

	    	// 網頁本身
	      	$('#MessageZone').append("Message received :" + JSON.stringify(payload) + "<br><br>")

	      //如果可以顯示通知就做顯示通知
	        if (Notification.permission === 'granted') {
	            notifyMe(payload);
	        }
	    });

	  // 視窗提示訊息
		  function notifyMe(payload) {

		  	if (!("Notification" in window)) {
		  		console.log("This browser does not support desktop notification");
		   	}
		   	else if (Notification.permission === "granted") {
	    		show_win(payload);
		   	}
		   	else if (Notification.permission !== 'denied' || Notification.permission === "default") {
		   		// 再次請求授權
			    	Notification.requestPermission(function (permission) {
				    	if (permission === "granted") {
				    		show_win(payload);
				     	};
				    });
		  	};
		  };

		// 視窗訊息
			function show_win(payload){

		    console.log('onMessage: ', payload);
		    var notifyMsg = payload.data;
		    var notification = new Notification(notifyMsg.title,
		    {
		        body: notifyMsg.body,
		        icon: notifyMsg.icon
		    });

		    notification.onclick = function (e) { // 綁定點擊事件
		        e.preventDefault(); // prevent the browser from focusing the Notification's tab
		        window.open(notifyMsg.click_action);
		    }

      	// var notification = new Notification(MessageContent);
      	// setTimeout(notification.close.bind(notification), 2000);
			}

	 	// 刪除 Device Token 的動作
		  $("#deleteToken").click(function() {

	 			//取得Token
			  	messaging.getToken()
			  	.then(function(currentToken) {

						//刪除後台token
							sendTokenToServer(currentToken,1);

						// 刪除Token
			    		messaging.deleteToken(currentToken)
			    		.then(function() {
			      		console.log('Token deleted.');
			     		})
			     		.catch(function(err) {
			      		console.log('Unable to delete token. ', err);
			     		});
			    })
			    .catch(function(err) {
			    	console.log('Error retrieving Instance ID token. ', err);
			    });
		  });

	  // 要求 Device Token 的動作
		  $("#requestPermission").click(function() {

		  	// 允許請求
			    messaging.requestPermission()
		    	.then(function() {
		    		// 獲得允許
		    		console.log('Notification permission granted.');
	   				messaging.getToken()	// 取得Token
	 					.then(function (currentToken) {

							//紀錄token
								sendTokenToServer(currentToken,2);

							// 顯示Token
				      	if (currentToken) {
				       		$("#Token").html("<br/>Device Token:<br/><br/>"+currentToken);
				      	} else {
				       		$('#Token').html('Get Token Failed');
				      	};
	     			})
	 					.catch(function(err) {
	  					$('#Token').html('Unable to get permission to send message 1');
	 					});
		    	})
		    	.catch(function(err) {
				    $('#Token').html('Unable to get permission to send message 2');
			    });
		  });

	  // 紀錄Token
		  function 	sendTokenToServer(currentToken,mode){

				$.ajax({
					url: 'change_token.php',
					type: 'POST',
					dataType: 'json',
					async:false,
					data: {
						'token':currentToken,
						'change':mode
					},
		   		error: function (xhr,textStatus, errorThrown) {
						alert("發生錯誤"+errorThrown);
		        			return false;
		   		},
					success: function(data){
						if(data.code==0){
						}
					}
				});
			}

	});

 </script>

<button id="requestPermission">Request Permission</button>

<button id="deleteToken">deleteToken</button>

<div id="Token" style="max-width:300px;word-break: break-all;"></div>
<br><hr><br>
<div id="MessageZone"></div>


firebase-messaging-sw.js 部分

importScripts('https://www.gstatic.com/firebasejs/4.6.1/firebase-app.js');
importScripts('https://www.gstatic.com/firebasejs/4.6.1/firebase-messaging.js');

firebase.initializeApp({
  'messagingSenderId': 'G-GQ27ZK9QBW'
});
const messaging = firebase.messaging();

messaging.setBackgroundMessageHandler(function (payload) {
    console.log('Received background message ', payload);

		const notificationTitle = payload['Title'];
		const notificationOptions = {
		  body: '1',
		  icon: 'https://www.ruten.com.tw/images/logo_s.gif',
		  click_action: 'https://mybid.ruten.com.tw/master/my.php'
		};

		return self.registration.showNotification(notificationTitle, notificationOptions);
});

self.addEventListener('install', function() {
   self.skipWaiting();
});

console.log("Loaded SW..");
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

1 個回答

2
listennn08
iT邦高手 5 級 ‧ 2019-12-26 13:20:27
最佳解答

根據這篇 iOS Push Notifications: Are we there yet? (Hint: Almost) [2019]
指出 在 iOS 11.3 以後 safari 是不支援推播通知的
如果你是要測試在 safari 上是否運作正常可以放到 macos 上測試

看更多先前的回應...收起先前的回應...
tsaipowun iT邦新手 5 級 ‧ 2019-12-26 14:25:02 檢舉

感謝回答,沒有MAC可以測試。。。
另外 Service Work 在11.3版已後有支援呦

我沒有說 Service Work 不支援
我是說 不支援 push-notification

As you can see, Safari iOS has finally supported service workers in iOS 11.3. But what is on hold, is their support for Web Push Notifications. So push notification iOS is currently not available.

文章內也有提到
11.3支援 Service Work 但暫停支援推播通知

有看另外一篇提及可能會在 2020 年支援推播通知

tsaipowun iT邦新手 5 級 ‧ 2019-12-26 16:35:58 檢舉

感謝回覆,不知目前是否有其他方式用WEB推播 iOS的裝置

tsaipowun iT邦新手 5 級 ‧ 2019-12-26 16:48:29 檢舉

這篇文章,是不是指可以
用Safari接收推播(對iOS完全不懂的人) https://support.apple.com/zh-tw/guide/safari/sfri40734/mac

依目前看來蘋果短時間內是不會讓 web 可以做推播通知
蘋果是提倡用戶下載 app 的
因為可以賺錢

這篇文章,是不是指可以
用Safari接收推播(對iOS完全不懂的人) https://support.apple.com/zh-tw/guide/safari/sfri40734/mac

您找的這篇文章是指的是 mac 上的 safari

tsaipowun iT邦新手 5 級 ‧ 2019-12-26 17:05:09 檢舉

感謝回覆..

我要發表回答

立即登入回答