首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何将PWA与Next.js集成以支持通知和推送通知

如何将PWA与Next.js集成以支持通知和推送通知
EN

Stack Overflow用户
提问于 2020-09-24 22:33:59
回答 1查看 4.1K关注 0票数 8

我正在用next.js构建一个PWA,并且一直有一些问题。

我正在尝试将设备运动集成到我的用户帐户和地理位置,然后是通知。

基于此存储库https://github.com/shadowwalker/next-pwa/和本教程https://medium.com/@sarafathulla/how-to-add-firebase-push-notifications-in-next-js-react-8eecc56b5cab

以及这些接口,https://whatwebcando.today/device-motion.htmlhttps://whatwebcando.today/geolocation.html

目前PWA是使用next-pwa的样板,

next.config.js

代码语言:javascript
复制
module.exports = withPWA({
  pwa: {
    disable: process.env.NODE_ENV === 'development',
    dest: 'public',
    runtimeCaching,  
  },
  poweredByHeader: false,
},
withBundleAnalyzer(),

)

我非常困惑如何将简单的设备运动集成到PWA中,以及如何在总体上向前发展。

如果有人能给我指出正确的方向,那就太棒了!所以不同于通常的web dev代码。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-02-11 14:09:30

这对我很有效

代码语言:javascript
复制
// public/firebase-messaging-sw.js
importScripts('https://www.gstatic.com/firebasejs/7.9.1/firebase-app.js');
importScripts('https://www.gstatic.com/firebasejs/7.9.1/firebase-messaging.js');

firebase.initializeApp({
  apiKey: '****',
  authDomain: '*****',
  projectId: '*****',
  storageBucket: '******',
  messagingSenderId: '*****',
  appId: '*****',
  measurementId: '*****',
});

firebase.messaging();

//background notifications will be received here
firebase.messaging().setBackgroundMessageHandler((payload) => {
  const { title, body } = JSON.parse(payload.data.notification);
  var options = {
    body,
    icon: '/icons/launcher-icon-4x.png',
  };
  registration.showNotification(title, options);
});

// webpush.js
import 'firebase/messaging';
import firebase from 'firebase/app';
import localforage from 'localforage';

const firebaseCloudMessaging = {
  //checking whether token is available in indexed DB
  tokenInlocalforage: async () => {
    return localforage.getItem('fcm_token');
  },

  //initializing firebase app
  init: async function () {
    if (!firebase.apps.length) {
      firebase.initializeApp({
        apiKey: '****',
        authDomain: '*****',
        projectId: '*******',
        storageBucket: '******',
        messagingSenderId: '******',
        appId: '*****',
        measurementId: '*******',
      });

      try {
        const messaging = firebase.messaging();
        const tokenInLocalForage = await this.tokenInlocalforage();

        //if FCM token is already there just return the token
        if (tokenInLocalForage !== null) {
          return tokenInLocalForage;
        }

        //requesting notification permission from browser
        const status = await Notification.requestPermission();
        if (status && status === 'granted') {
          //getting token from FCM
          const fcm_token = await messaging.getToken();
          if (fcm_token) {
            //setting FCM token in indexed db using localforage
            localforage.setItem('fcm_token', fcm_token);
            //return the FCM token after saving it
            return fcm_token;
          }
        }
      } catch (error) {
        console.error(error);
        return null;
      }
    }
  },
};
export { firebaseCloudMessaging };

// _app.js
import { firebaseCloudMessaging } from '../webPush';
import firebase from 'firebase/app';

useEffect(() => {
    setToken();
    async function setToken() {
      try {
        const token = await firebaseCloudMessaging.init();
        if (token) {
          getMessage();
        }
      } catch (error) {
        console.log(error);
      }
    }
    function getMessage() {
      const messaging = firebase.messaging();
      console.log({ messaging });
      messaging.onMessage((message) => {
        const { title, body } = JSON.parse(message.data.notification);
        var options = {
          body,
        };
        self.registration.showNotification(title, options);
      });
    }
  });
票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/64048718

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档