shahryarjb

shahryarjb

How to send push notification with Pigeon when we have subscriptions

Hi, I created a subscription with my service worker and pushManager in JavaScript side like this:

var vapidPublicKey = 'MY_PUBLIC_KEY';
var convertedVapidPublicKey = urlBase64ToUint8Array(vapidPublicKey);
return reg.pushManager.subscribe({
  userVisibleOnly: true,
  applicationServerKey: convertedVapidPublicKey,
});

After that, I have something like this in my database:

{
  "endpoint": "https://fcm.googleapis.com/fcm/send/USER_STUFF",
  "keys": {
    "auth": "AUTH_CODE",
    "p256dh": "P256DH_CODE"
  }
}

So I see the Pigeon support FCM, but when I want to send a notification as the document says, what is the TOKEN?

n = Pigeon.FCM.Notification.new({:token, "reg ID"}, %{"body" => "test message"})
YourApp.FCM.push(n)

My goal: I am creating a PWA application and I need to send push notification with service worker. It can be Chrome or Firefox, even in desktop or mobile. The user activates and adds the app to their operating system with a manifest. After that, I should be able to send notifications from the server to the user.

In JavaScript or node server I can send notification with web-push lib, but in elixir I need to send

Thank you in andvance

Most Liked

shahryarjb

shahryarjb

Yes, sure.
First of all, I have used GitHub - danhper/elixir-web-push-encryption: Elixir implementation of Web Push Payload encryption..

I have a JavaScript file for service worker, sw.js

self.addEventListener('push', function(event) {
  console.log('Push Notification received', JSON.parse(event.data.text()));

  var data = {title: 'New!', content: 'Something new happened!', openUrl: '/'};

  if (event.data) {
    data = JSON.parse(event.data.text());
  }

  var options = {
    body: data.content,
    icon: '/src/images/icons/app-icon-96x96.png',
    badge: '/src/images/icons/app-icon-96x96.png',
    data: {
      url: data.openUrl
    }
  };

  event.waitUntil(
    self.registration.showNotification(data.title, options)
  );
});

This is a addEventListener with push event and my service worker is registered in my app.js


app.js

if ('serviceWorker' in navigator) {
  navigator.serviceWorker
    .register('/sw.js')
    .then(function () {
      console.log('Service worker registered!');
    })
    .catch(function (err) {
      console.log(err);
    });
}

After that, you need user permission, for example when he/her clicks on a button. Like this:

var enableNotificationsButtons = document.querySelectorAll('.enable-notifications');

if ('Notification' in window && 'serviceWorker' in navigator) {
  for (var i = 0; i < enableNotificationsButtons.length; i++) {
    enableNotificationsButtons[i].style.display = 'inline-block';
    enableNotificationsButtons[i].addEventListener('click', askForNotificationPermission);
  }
}

I got all the buttons with .enable-notifications class CSS and gave them addEventListener with click event.

You can see my app.js here: app.js · GitHub

finally, I use the elixir library:

body = ~s({"title":"New Post","content":"New Post added!","openUrl":"/help"})
subscription = %{
  keys: %{
    p256dh: "CODE_OF_p256dh", 
    auth: "CODE_OF_auth" 
  }, 
  endpoint: "https://fcm.googleapis.com/fcm/send/FCM_TOKEN"
}

{:ok, response} = WebPushEncryption.send_web_push(body, subscription)
mayel

mayel

Thanks, much appreciated! I’ll give it another go :grinning:

Where Next?

Popular in Questions Top

Harrisonl
We have an ECS cluster with 4 services, where each task joins a single cluster, via discovery ECS discovery service. Currently when I de...
New
Brian
What is the proper way to load a module from a file in to IEX? In the python world, doing something like this pretty standard: from ....
New
albydarned
Hello all! I am typing this post from my new MacBook Pro with the M1 chip. I’m loving it so far, and will probably use it as my daily dr...
New
pgiesin
This should be a simple problem but I just can’t seem to figure it out. I have a standalone Elixir app that won’t find the database. Dep...
New
ycv005
I have followed this StackOverflow post to install the specific version of Erlang. And When I am running mix ecto.setup then getting fol...
New
lk-geimfari
What is most correct way to open, read and parse JSON file with poison? For example if we have example.json file in root of some projec...
New
gonzofish
I’m currently trying to understand how to join three tables using Ecto. All the examples I’ve seen use 2, so maybe I’m just missing somet...
New
shahryarjb
Hello, I have map which I want to convert it to string like this: the map: %{last_name: "tavakkoli", name: "shahryar"} the string I ne...
New
Fl4m3Ph03n1x
About me? ( if you have nothing better to do than reading about some random guy in the internet :stuck_out_tongue: ) Hello all, this is ...
New
skosch
To my knowledge, put_in, Map.update etc. all have the one limitation of not automatically creating intermediate keys when needed (for exa...
New

Other popular topics Top

JDanielMartinez
Hi! May someone helps me, please! I have two apps into an umbrella project: the first one is Database, which manages queries, and the se...
New
Patoshizzle
After calling mix ecto.create I get this error: 17:00:32.162 [error] GenServer #PID&lt;0.412.0&gt; terminating ** (Postgrex.Error) FATAL...
New
openscript
Hello! Sorry for this astonishing simple question, but I’m really stuck. I try to set up the intellij-elixir plugin, but I don’t know ho...
New
jerry
Good day to you all. I have been struggling to get a query involving like and ilike to work. Can anyone assist me on this, please? pro...
New
sergio
I couldn’t find any guides that worked well with Phoenix 1.6.0 and esbuild. I hope this helps people test the waters and eases you into t...
New
axelson
This post is a wiki (feel free to hit the edit button near the bottom right of this post to add your own changes!) This post collects co...
239 45766 226
New
_russellb
I want to try my hand at web scraping. What tools/libraries do I need to use. I’m hoping to turn this into something professional so don’...
New
script
If I have a string “1000 cfu/ml” . I want to remove the characters and / and space . So the string is like this "1000" What is the ...
New
aadeshere1
I have a another noob question about loop. Since elixir is immutable, while loop is not directly possible. total = 10 while total != 0 ...
New
fireproofsocks
Forgive me if this is obvious, but how does one delete a database record WITHOUT selecting it first? https://hexdocs.pm/ecto/Ecto.Repo.h...
New

We're in Beta

About us Mission Statement