Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

298
Visualizações
How to pass Laravel CSRF token to Service Worker so i can make a POST request?

So I've got a Laravel application that utilises a service worker for caching and web push notifications. I'm trying to pass an action to the web push notifications so when it pops up on the users device, it gives them 2 options - Accept or Reject. Clicking on either of these options will fire off a POST request to my Laravel application updating the users status. Here is my service-worker.js file:

self.addEventListener('notificationclick', function(event) {
    console.log('[Service Worker] Notification click Received.');

    var notification = event.notification;
    var action = event.action;

    notification.close();

    switch (action) {
        case 'close':
            console.log('[Service Worker] close Action Clicked');
            break;
        case 'view':
            console.log('[Service Worker] view Action Clicked')
            event.waitUntil(clients.openWindow(notification.data.url));
            break;
        case 'accept-player':
            console.log('[Service Worker] accept-player Action Clicked')

           fetch(notification.data.url, {
                method: 'POST',
                headers: {
                    'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').content
                },
                body: { accepted:1 },
            }).catch(error => {
               console.error(error)
           });

            break;
        case 'reject-player':
            console.log('[Service Worker] reject-player Action Clicked')
            fetch(notification.data.url, {
                method: 'POST',
                headers: {
                    'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').content
                },
                body: { accepted:0 },
            }).catch(error => {
                console.error(error)
            });
            break;
    }
});

Within my switch, i'm specifically referring to accept-player and reject-player cases for the fetch.

Typically I get the CSRF token from my HTML HEAD but in this case document doesn't exist so it can't get it. I get the following error in console:

sw.js:86 Uncaught ReferenceError: document is not defined

How can I pull in the CSRF token to my service-worker.js so I can make a POST request?

I did some reading and I'm not sure whether I should be disabling CSRF verification for this one particular route either.

Hoping someone can help with this.

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

This is proving quite difficult and I decided to change my approach. Although disabling CSRF verification on this particular route is helpful, my route requires Auth and the service worker has no Auth setup to handle the request.

Instead of doing a POST request from my service-worker to my app, I am doing a redirect to another GET route with some additional parameters e.g. "showPlayersPending=1". Then in my view, I am merely wrapping an if around the request if it has "showPlayersPending" then to show the modal on load so the authenticated user can action the POST request.

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda