[英]Firebase Cloud Messaging without hosting (Web/JavaScript)
在瀏覽Firebase Cloud Messaging的官方視頻教程時,如果不托管應用程序,則無法獲得消息傳遞令牌。
這是我的app.js
文件:
/* global firebase */
// Initialize Firebase
var config = {
apiKey: 'AIzaSyBYfb9HAi_oE-PKqFNkRQcxAgLU-nm8sIE',
authDomain: 'web-quickstart-c0309.firebaseapp.com',
databaseURL: 'https://web-quickstart-c0309.firebaseio.com',
projectId: 'web-quickstart-c0309',
storageBucket: 'web-quickstart-c0309.appspot.com',
messagingSenderId: '713880824056'
}
firebase.initializeApp(config)
const messaging = firebase.messaging()
messaging.requestPermission()
.then(() => {
console.log('Permission granted.')
return messaging.getToken()
.then(token => {
console.log('messaging token test:', token)
return token
})
.catch(error => {
console.log('messaging error:', error)
})
})
.then(token => {
console.log('permission token test:', token)
})
.catch(error => {
console.log('permission error:', error)
})
我的根目錄中有一個firebase-messaging-sw.js
文件。
當我直接在瀏覽器中加載index.html
文件並接受對話框時,我收到該令牌的未定義值。 完整的控制台輸出為:
16:20:35.744 app.js:17 Permission granted.
16:20:35.750 app.js:20 messaging token test: null
16:20:35.751 app.js:28 permission token test: null
如果我通過將firebase.json
文件編輯為以下內容來托管應用程序:
{
"hosting": {
"public": "./"
}
}
然后運行firebase serve -p 8081
,打開http://localhost:8081
,並接受對話框,我確實收到了令牌。 完整的輸出是:
16:23:42.902 app.js:17 Permission granted.
16:23:43.059 app.js:20 messaging token test: eyd1EaFwULQ:APA91bGUZr9fAGcCaYVtXTPjk55AmpWLNdaqGapMa1S1GWTYeJwtJraEKuhAPpSM-v-2xPaSJQgTKRVosTN-0KRPHCccjdRZNDkegtW2HMC_mSbdap9h5TeH7KKQSbN4QrjVmIl7VZlu
16:23:43.060 app.js:28 permission token test: eyd1EaFwULQ:APA91bGUZr9fAGcCaYVtXTPjk55AmpWLNdaqGapMa1S1GWTYeJwtJraEKuhAPpSM-v-2xPaSJQgTKRVosTN-0KRPHCccjdRZNDkegtW2HMC_mSbdap9h5TeH7KKQSbN4QrjVmIl7VZlu
這是有記錄的約束嗎? 是否可以在不托管應用程序的情況下接收令牌?
FCM僅在https協議提供的頁面中工作
僅在通過HTTPS服務的頁面中支持FCM SDK。 這是由於使用了服務工作者,僅在HTTPS站點上可用。 需要提供者? Firebase托管是一種在您自己的域上獲取免費HTTPS托管的簡便方法。
以及您是否想知道為什么localhost可以工作,因為localhost中的頁面就像由https服務一樣
所以 有沒有辦法在不托管應用程序的情況下接收令牌?
答案是:您的網頁不應由https協議提供服務
我不會說這是確切的替代方案,但是是解決該問題的替代方案,您可以使用ngrok ,它將為您提供Https訪問權限,以表示localhost
替代方法。
因此,安裝后,請使用FCM中ngrok在終端上輸出的任何URL。
注意 :ngrok同時輸出http
和https
URL,因此請使用Only Https
。 它們仍然映射到您的本地服務器。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.