我正在try 以下代码:

    navigator.serviceWorker.register('service-worker.js')
      .then((registration) => {
        const messaging = firebase.messaging().useServiceworker(registration)
        console.log(messaging)
        messaging.requestPermission().then(function () {
          console.log('Notification permission granted.')
          messaging.getToken().then(function (currentToken) {
            if (currentToken) {
              console.log(currentToken)
            }
          })
        })
      })

我的 list :

{
  "name": "Herot-Eyes",
  "short_name": "herot-eyes",
  "gcm_sender_id": "103953800507",
  "icons": [
    {
      "src": "/static/img/icons/herot-eyes-192x192.png",
      "sizes": "192x192",
      "type": "image/png"
    },
    {
      "src": "/static/img/icons/herot-eyes-512x512.png",
      "sizes": "512x512",
      "type": "image/png"
    },
    {
      "src": "/static/img/icons/apple-touch-icon-180x180.png",
      "sizes": "180x180",
      "type": "image/png"
    }
  ],
  "start_url": "/",
  "display": "fullscreen",
  "orientation": "portrait",
  "background_color": "#000000",
  "theme_color": "#2196f3"
}

出什么事了?我的控制台.日志(log)(消息)返回出厂错误,如下所示:

错误推送集:"用于存储/查找的FCM推送集不正确

"服务工作者作用域必须是至少包含一个

"请确保在中正确设置了"messagingSenderId"

"订阅必须是有效的PushSubscription."不好的标记:"这个

"公共VAPID密钥不是65字节的UINT8array."

"setBackgroundMessageHandler()的输入必须是函数."

"无法执行服务工作者范围的删除try

"无法作为令牌执行令牌的删除try

"无法删除乏味的密钥."

"我们无法注册默认的服务人员.

"无法删除当前保存的令牌."获取订阅失败

"try 获取任何现有推送时出错

"请将您的web应用程序 list 的'gcm_sender_id'值更改为

"必须将有效令牌传递到deleteToken(),即来自的令牌."

"公钥必须是字符串."保存的令牌无效

"无法访问已保存令牌的详细信息."

"找不到FCM令牌,因此无法重新订阅.

"尽管服务人员注册成功,但仍存在一些问题

"试图向不存在的窗口客户端发送消息."

"通知已被阻止."仅在sw中可用

"此方法在服务工作者上下文中可用."

"此方法在窗口上下文中可用."权限被阻止

"所需的权限未被授予,而是被阻止."

"所需的权限未被授予,而是被取消."

"解密时,公钥不等于65字节."

"此方法应被扩展类重写."

"用于推送的服务人员被裁掉了."

"服务人员注册是预期的输入."

"向FCM订阅用户时出现问题:{$message}"

"获取FCM令牌时,FCM返回无效响应."

"FCM在订阅用户推送时未返回令牌."

"从FCM取消订阅用户时出现问题:{$message}"

"从FCM更新用户时出现问题:{$message}"

"FCM在更新要推送的用户时未返回令牌."

"为推送重新订阅FCM令牌时出错

"此浏览器不支持使用firebase所需的API

"在调用getToken()之前,必须调用useServiceWorker()以确保

推荐答案

配置服务器以接收通知

在公用文件夹中,将以下行添加到manifest.json:

{
    //...manifest properties
    "gcm_sender_id": "103953800507" <--- add this line to the file
}

Note: if the project wasn't created using Vue Cli, manually create the manifest.json file.(谢谢@natghi)

firebase消息软件.js

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

var config = {
  messagingSenderId: <Sender ID>
};
firebase.initializeApp(config);

let messaging = firebase.messaging();

在你的主要.js文件添加以下代码

var config = {
  apiKey: <API_KEY>,
  authDomain: <DOMAIN>,
  databaseURL: <DATABASE_URL>,
  projectId: <PROJECT_ID>,
  storageBucket: <STORAGE_BUCKET>,
  messagingSenderId: <SENDER_ID>
};
firebase.initializeApp(config);

Vue.prototype.$messaging = firebase.messaging()

navigator.serviceWorker.register('/firebase消息软件.js')
  .then((registration) => {
    Vue.prototype.$messaging.useServiceWorker(registration)
  }).catch(err => {
    console.log(err)
  })

接收通知

然后在你的应用程序中.vue,将此代码添加到created()函数中

created() {
    var config = {
        apiKey: <API_KEY>,
        authDomain: <DOMAIN>,
        databaseURL: <DATABASE_URL>,
        projectId: <PROJECT_ID>,
        storageBucket: <STORAGE_BUCKET>,
        messagingSenderId: <SENDER_ID>
    };
    firebase.initializeApp(config);
    const messaging = firebase.messaging();

    messaging
    .requestPermission()
    .then(() => firebase.messaging().getToken())
    .then((token) => {
        console.log(token) // Receiver Token to use in the notification
    })
    .catch(function(err) {
        console.log("Unable to get permission to notify.", err);
    });

    messaging.onMessage(function(payload) {
    console.log("Message received. ", payload);
    // ...
    });
}

发送通知

使现代化

const admin = require("firebase-admin")

var serviceAccount = require("./certificate.json");

admin.initializeApp({
    credential: admin.credential.cert(serviceAccount),
});
const Messaging = admin.messaging()

var payload = {
    webpush: {
        notification: {
            title: "Notification title",
            body: "Notification info",
            icon: 'http://i.imgur.com/image.png',
            click_action: "http://yoursite.com/redirectPage" 
        },
    },
    topic: "Doente_" + patient.Username
};

return Messaging.send(payload)

旧版本

然后,在"postman "中,您可以执行以下请求

POST /v1/projects/interact-f1032/messages:send HTTP/1.1
Host: fcm.googleapis.com
Authorization: Bearer <SENDER_TOKEN>
Content-Type: application/json

{
  "message":{
    "token" : The token that was in the console log,
    "notification" : {
      "body" : "This is an FCM notification message!",
      "title" : "FCM Message"
      }
   }
}

发送方令牌

在您的后端,使用以下代码,firebase仪表板中的文件"certificate.json"就是从中获得的(https://firebase.google.com/docs/cloud-messaging/js/client-生成密钥对)

const {google} = require('googleapis');

function getAccessToken() {
  return new Promise(function(resolve, reject) {
    var key = require('./certificate.json');
    var jwtClient = new google.auth.JWT(
      key.client_email,
      null,
      key.private_key,
      ["https://www.googleapis.com/auth/firebase", 
      "https://www.googleapis.com/auth/cloud-platform"],
      null
    );
    jwtClient.authorize(function(err, tokens) {
      if (err) {
        reject(err);
        return;
      }
      resolve(tokens.access_token);
    });
  });
}

getAccessToken().then(senderToken => console.log(senderToken))

senderToken在授权标头上用于发送通知

Vue.js相关问答推荐

设置Vite Vue 3需要多个应用程序输出目录

单击 v-data-table 中行中的任意位置并移动到另一个页面

混合使用 React 和 Vue 是个好主意吗?

nuxt.js - 预加载 .woff 字体加载为@font-face

Vue.js 和观察者模式

如何使 Rails 与 vue.js 一起工作?

在textbox文本框 VueJS 2 中键入时搜索列表

Django Rest 框架、CSRF 和 Vue.js

VueJS 组件中的图像未加载

此 set-cookie 已被阻止,因为它具有 samesite=lax

vue 在 v-model 之后执行 @click

我可以修改 Vue.js VNodes 吗?

如何在生产模式下为 chrome 扩展启用 Vue devtools?

如何在 Vuex 中获取 Vue 路由参数?

基本 vue.js 2 和 vue-resource http 获取变量赋值

如何确定 Vue 何时完成更新 DOM?

Vue路由在新页面上回到顶部

Vue 2 转换不起作用

Vue 3 组合 API 数据()函数

使用 svelte js 的原因