• Что бы вступить в ряды "Принятый кодер" Вам нужно:
    Написать 10 полезных сообщений или тем и Получить 10 симпатий.
    Для того кто не хочет терять время,может пожертвовать средства для поддержки сервеса, и вступить в ряды VIP на месяц, дополнительная информация в лс.

  • Пользаватели которые будут спамить, уходят в бан без предупреждения. Спам сообщения определяется администрацией и модератором.

  • Гость, Что бы Вы хотели увидеть на нашем Форуме? Изложить свои идеи и пожелания по улучшению форума Вы можете поделиться с нами здесь. ----> Перейдите сюда
  • Все пользователи не прошедшие проверку электронной почты будут заблокированы. Все вопросы с разблокировкой обращайтесь по адресу электронной почте : info@guardianelinks.com . Не пришло сообщение о проверке или о сбросе также сообщите нам.

? How i added a web push notification feature in my project

Lomanu4 Оффлайн

Lomanu4

Команда форума
Администратор
Регистрация
1 Мар 2015
Сообщения
1,481
Баллы
155
Hey everyone! ?

I am thrilled to announce to you that I have implemented a push notification feature on my

Пожалуйста Авторизируйтесь или Зарегистрируйтесь для просмотра скрытого текста.

project.
Now you can get real-time updates even when you’re not on the ChatX tab. Anytime someone sends you a message, you’ll get a notification straight to your device.

How it works

1. Service Worker



A

Пожалуйста Авторизируйтесь или Зарегистрируйтесь для просмотра скрытого текста.

is a JavaScript file that runs in the background of your browser independently from the web page. It allows your app to handle things like push notifications, background syncing, and caching even when the user is not actively on your site.

2. VAPID Keys


These are cryptographic keys that authenticate your server with the browser’s push service. They allow you to send web push notifications securely and directly, without relying on external services like Firebase Cloud Messaging (FCM).

3. Subscription


When a user allows push notifications, the browser creates a subscription object containing an endpoint URL and encryption keys. This subscription is sent to your backend and used to identify and securely send push messages to that user’s device.

Overall Idea


We prompt the user to accept permissions for notification


  1. Service Worker: We register a Service worker. Its job is to listen for push events and trigger notifications sent from the server.


  2. Subscribing to PushManager:
    After permission is granted, we subscribe the user to push notifications through the browser’s

    Пожалуйста Авторизируйтесь или Зарегистрируйтесь для просмотра скрытого текста.

    . This returns a subscription object with the endpoint and keys, which we send to our backend to store.

async function subscribeUser() {
const registration = await navigator.serviceWorker.ready;
const subscription = await registration.pushManager.subscribe({
userVisibleOnly: true,
applicationServerKey: '<YOUR_PUBLIC_VAPID_KEY>'
});
// Send the subscription payload to the server to store
await fetch('/api/save-subscription', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(subscription)
});
}

3 Sending Notifications from the Server:
When there is a new chat message, the server uses the saved subscriptions to send push notifications via the Web Push Protocol using VAPID keys.


const webpush = require('web-push');

webpush.setVapidDetails(
'mailto:you@example.com',
process.env.VAPID_PUBLIC_KEY,
process.env.VAPID_PRIVATE_KEY
);

async function sendNotification(subscription, payload) {
await webpush.sendNotification(subscription, JSON.stringify(payload));
}
4. Handling Push Events in the Service Worker:


The Service Worker listens for push events and displays notifications to the user.


self.addEventListener('push', event => {
const data = event.data.json();
event.waitUntil(
self.registration.showNotification(data.title, {
body: data.body,
icon: '/icon.png',
data: { url: data.url }
})
);
});

self.addEventListener('notificationclick', event => {
event.notification.close();
event.waitUntil(clients.openWindow(event.notification.data.url));
});

Next up:

  • Video Chatting functionality using WebRTC
  • Add and remove users from a group

You can check it out live:

Пожалуйста Авторизируйтесь или Зарегистрируйтесь для просмотра скрытого текста.




Пожалуйста Авторизируйтесь или Зарегистрируйтесь для просмотра скрытого текста.

 
Вверх Снизу