How to make a push notification using vite-plugin-pwa?

170 Views Asked by At

I'm stuck on the push notification and I don't know what to do next here my vite.config file:

    import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'
import { VitePWA } from 'vite-plugin-pwa'

const vitePWA = VitePWA({
  srcDir: 'src/service-worker',
  registerType: 'autoUpdate',
  outDir: "dist/",
  strategies: 'injectManifest',
  injectRegister  : 'auto',
  filename: 'sw.js',
  includeAssets: ['favicon.ico', 'apple-touch-icon.png', 'masked-icon.svg'],
  devOptions: {
    enabled: true,
    type: 'module',
  },
  manifest: {
    name: 'VitePwa',
    short_name: 'PWA',
    theme_color: '#fff',
    icons: [
      {
        src: 'public/android-chrome-192x192.png',
        sizes: '192x192',
        type: 'image/png'
      },
      {
        src: 'public/android-chrome-512x512.png',
        sizes: '512x512',
        type: 'image/png'
      },
      {
        src: 'public/android-chrome-512x512.png',
        sizes: '512x512',
        type: 'image/png',
        purpose: 'any maskable'
      }
    ]
  }
})
export default defineConfig({
  plugins: [react(), vitePWA],
})

my workbox is described in another file and everything works correctly there when building sw.js is generated in the dist directory

here is my own service worker file:

    import { precacheAndRoute } from "workbox-precaching"

precacheAndRoute(self.__WB_MANIFEST || [])

self.addEventListener('install', () => void self.skipWaiting())
self.addEventListener('activate', () => void self.clients.claim())

self.addEventListener('push', e => {
    if (!(self.Notification && self.Notification.permission === 'granted')) {
        console.log('123123')
        return
    }

    if (e.data){
        const data = e.data.json()
        console.log(e.data)
        self.registration.showNotification(data.title, {
            body: data.message,
            tag: data.tag,
            icon: data.icon,
        })
    }
})

self.addEventListener('notificationclick', e => {
    e.waitUntil(self.clients.openWindow(e.notification.tag))
    e.notification.close()
})

when you enter text and try to enter a text stream in the console, you get a so-called Uncaught syntax error: unexpected token 'T', "Test push"... invalid JSON in sw.js:1224:22

I read in the documentation that https is needed for it, but I'm not sure if that's the case, correct me

0

There are 0 best solutions below