I cannot make Firebase Cloud Messaging notification work in the web browser

Asked

Viewed 454 times

0

I’m really lost on how to make notifications work. I find their documentation very confusing. But following as I understood and some tutorials, I think I managed to solve a good part and should be missing little.

I’ll spend everything I’ve ever done:

In the foreground on the homepage is like this:

<script src="https://www.gstatic.com/firebasejs/5.6.0/firebase-app.js"></script>
<script src="https://www.gstatic.com/firebasejs/5.6.0/firebase-messaging.js"></script>
<script>
    var config = {
    apiKey: "meu api key",
    authDomain: "meusite.firebaseapp.com", // Tenho dominio próprio e não sei se devo colocar ele aqui.
    databaseURL: "https://meusite.firebaseio.com", // Não sei pra que serve isso.
    projectId: "meusite",
    storageBucket: "",
    messagingSenderId: "470112242644" // Não lembro da onde eu tirei esse número.
  };
  firebase.initializeApp(config);
    const messaging = firebase.messaging();

    navigator.serviceWorker.register('plugins/firebase/firebase-messaging-sw.js').then((registration) => {
        messaging.usePublicVapidKey("um key que uso que tbm não lembro de onde tirei");
        messaging.useServiceWorker(registration);

        messaging.requestPermission().then(function() {
           console.log('Notification permission granted.');
           if(isTokenSentToServer()){
               console.log('Token ja salvo.');
           } else {
           getRegToken();
       }
       }).catch(function(err) {
         console.log('Unable to get permission to notify.', err);
       });
  });
  function getRegToken() {
        messaging.getToken().then(function(currentToken) {
          if (currentToken) {
            saveToken(currentToken);
            console.log(currentToken);
            setTokenSentToServer(true);
          } else {
            console.log('No Instance ID token available. Request permission to generate one.');
            setTokenSentToServer(false);
          }
        }).catch(function(err) {
          console.log('An error occurred while retrieving token. ', err);
          showToken('Error retrieving Instance ID token. ', err);
          setTokenSentToServer(false);
        });
  }

  function setTokenSentToServer(sent) {
    window.localStorage.setItem('sentToServer', sent ? '1' : '0');
  }

  function isTokenSentToServer() {
    return window.localStorage.getItem('sentToServer') === '1';
  }

  function saveToken(currentToken) {
      // Enviar Token para firebase database
  }

  messaging.onMessage(function(payload) {
      console.log('Mensagem Recebida ', payload);
       notificationTitle = payload.data.title;
       notificationOptions = {
          body: payload.data.body,
          icon: payload.data.icon,
          image: payload.data.image
        };

        var notification = new Notification(notificationTitle, notificationOptions);
  });
</script>

So far I can get the browser token, but I don’t know where to store it. In the tutorial I saw, I would have to put in a database of my own, but then send msg one by one. And I think that I would have problems sending msg to more than 100 thousand people who request notifications. So I thought it would be better to do by topics, but I can’t imagine how it’s done, and I’d really like some help with that.

In the serviceworker archive firebase-messaging-sw.js is as follows:

importScripts('https://www.gstatic.com/firebasejs/5.6.0/firebase-app.js');
importScripts('https://www.gstatic.com/firebasejs/5.6.0/firebase-messaging.js');
    var config = {
    apiKey: "meu api key",
    authDomain: "meusite.firebaseapp.com",
    databaseURL: "https://meusite.firebaseio.com",
    projectId: "meusite",
    storageBucket: "",
    messagingSenderId: "470112242644"
  };
// Até aqui tenho as mesmas duvidas do script na pagina inicial, e nem sei se precisa mesmo repetir tudo assim

  firebase.initializeApp(config);
var messaging = firebase.messaging();

// [START background_handler]
messaging.setBackgroundMessageHandler(function(payload) {
  console.log('[firebase-messaging-sw.js] Received background message ', payload);
  // Customize notification here
  var notificationTitle = payload.data.title;
  var notificationOptions = {
    body: payload.data.body,
    icon: payload.data.icon,
    image: payload.data.image
  };

  return self.registration.showNotification(notificationTitle,
    notificationOptions);
});
// [END background_handler]

I tried to test it through the firebase console, but I couldn’t get any messages, I don’t think it’s working. I made a script in php and tbm did not work to send msg.

The php script is as follows Firebasenotifications.class.php:

class FireBaseNotifications {
    private $serverAPiKey = "meu server key";
    private $tokens = [];
    private $firebaseurl = "https://fcm.googleapis.com/fcm/send";

    public function setServerAPiKey($serverAPiKey) {
        $this->serverAPiKey = $serverAPiKey;
    }

    public function setTokens($tokens) {
        $this->tokens = $tokens;
    }

    public function SendNotification($icon, $titulo, $mensagem, $image) {
        $msg = ['icon'=>$icon, 'title'=>$titulo, 'body'=>$mensagem, 'image'=>$image];
        $payloads = ['registration_ids' => $this->tokens, 'data' => $msg];
        return $this->CurlExecute($this->firebaseurl, $payloads);
    }

    private function getHeader() {
        return ['Authorization: Key='.$this->serverAPiKey,'Content-Type: Application/json'];
    }

    private function CurlExecute($url, $postfields) {
        $curl = curl_init();
        curl_setopt_array($curl, array(
            CURLOPT_URL => $url,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_CUSTOMREQUEST => "POST",
            CURLOPT_POSTFIELDS => json_encode($postfields),
            CURLOPT_HTTPHEADER => $this->getHeader()
        ));

        $result['response'] = curl_exec($curl);
        $result['err'] = curl_error($curl);

        curl_close($curl);
        return $result;
    }
}

I created this class alone and I don’t even know if I did it right, I’d like to adapt it to accept topics or devices, but I don’t know how it does it. If anyone has any ideas and can guide me, I would really appreciate it.

And to use the link above I do so:

$fbcn = new FireBaseNotifications();
$fbcn->setTokens(["token do usuario 1", "token do usuário 2"...]);
$fbcn->SendNotification("linkDeImagemDoIcone.jpg", "Titulo da Mensagem", "Minha Mensagem", "linkDeImagemdaNotificacao.jpg");

But none of this is working yet. I’m totally lost. And everything I find on the net is in English. And what I find in Portuguese is only for android app, I can’t find anything for web version.

Could someone help me and explain me a little better about how it works and how to work with topics and devices??

1 answer

0

I was in the same trouble, but so it worked:

In my index:

<script src="https://www.gstatic.com/firebasejs/5.6.0/firebase.js"></script>
<script src="https://www.gstatic.com/firebasejs/5.6.0/firebase-app.js"></script>
<script src="https://www.gstatic.com/firebasejs/5.6.0/firebase-messaging.js"></script>
<script src="firebase-messaging-sw.js"></script>
<script type="text/javascript">
  var config = {
    apiKey: "[sua api]",
    authDomain: "[ seu domain]",
    databaseURL: "[ tanto domain quanto essa são opcionais, mas eu coloquei ]",
    projectId: "[ seu prject id]",
    storageBucket: "[ storage]",
    messagingSenderId: "[ seu sender]"
  };
firebase.initializeApp(config);
const messaging = firebase.messaging();
// Add the public key generated from the console here.
messaging.usePublicVapidKey("[sua key ]");
messaging.requestPermission().then(function() {
  console.log('Notification permission granted.');
  vai();
  // TODO(developer): Retrieve an Instance ID token for use with FCM.
  // ...
}).catch(function(err) {
  console.log('Unable to get permission to notify.', err);
});
var vai = function (){
  messaging.getToken().then(function(currentToken) {
    if (currentToken) {
      console.log(currentToken)
      //sendTokenToServer(currentToken);
      //updateUIForPushEnabled(currentToken);
    } else {
      // Show permission request.
      console.log('No Instance ID token available. Request permission to generate one.');
    }
  }).catch(function(err) {
    console.log('An error occurred while retrieving token. ', err);
    //showToken('Error retrieving Instance ID token. ', err);
    //setTokenSentToServer(false);
  });
}
messaging.onMessage(function(payload) {
  // Messages received. Either because the
  // app is running in the foreground, or
  // because the notification was clicked.
  // `payload` will contain your data.
  console.log("Message received. ", payload);
  var notification = new Notification(payload.data.title, {
      icon: '[ logo]',
      body: payload.data.message,
    });
notification.onclick = function () {
      window.open("[ link a abrir]");      
    }
});
</script>

in firebase-messaging-sw.js:

importScripts('https://www.gstatic.com/firebasejs/4.8.1/firebase-app.js');
importScripts('https://www.gstatic.com/firebasejs/4.8.1/firebase-messaging.js');
  var config = {
    apiKey: "[ sua key]",
    authDomain: "[ domain]",
    databaseURL: "[ url]",
    projectId: "[ projeto]",
    storageBucket: "[ storage]",
    messagingSenderId: "[ SENDER ID]"
  };
firebase.initializeApp(config);
const messaging = firebase.messaging();
messaging.setBackgroundMessageHandler(function(payload) {
  console.log('[firebase-messaging-sw.js] Received background message ', payload);
  // Customize notification here
  var notificationTitle = payload.data.title;
  var notificationOptions = {
    body: payload.data.body,
    icon: payload.data.icon,
    image: payload.data.image
  };
return self.registration.showNotification(notificationTitle,notificationOptions);
});

for some reason always calls the "firebase-messaging-sw.js" at the root of the localhost, so check it out tbm

your php ta more organized than me mine, but my ta so:

<?php
$to="[tokem que vai receber]";
$title="Olá! :D";
$message="Teste de Notificação :D";
sendPush($to,$title,$message);

function sendPush($to,$title,$message)
{
// API access key from Google API's Console
// replace API
define( 'API_ACCESS_KEY', '[chave do servidor]');
$registrationIds = array($to);
$msg = array
(
'message' => $message,
'title' => $title

// you can also add images, additionalData
);
$fields = array
(
'registration_ids' => $registrationIds,
'data' => $msg
);
$headers = array
(
'Authorization: key=' . API_ACCESS_KEY,
'Content-Type: application/json'
);
$ch = curl_init();
curl_setopt( $ch,CURLOPT_URL, 'https://fcm.googleapis.com/fcm/send' );
curl_setopt( $ch,CURLOPT_POST, true );
curl_setopt( $ch,CURLOPT_HTTPHEADER, $headers );
curl_setopt( $ch,CURLOPT_RETURNTRANSFER, true );
curl_setopt( $ch,CURLOPT_SSL_VERIFYPEER, false );
curl_setopt( $ch,CURLOPT_POSTFIELDS, json_encode( $fields ) );
$result = curl_exec($ch );
curl_close( $ch );
echo $result;
}
?>

  • Thank you for answering, I only saw your answer today. I’m sorry for the delay. I’ll take a closer look at your code and see where I’m going wrong. Then I’ll come back here to answer if it’s okay?? Thank you

Browser other questions tagged

You are not signed in. Login or sign up in order to post.