0

I am listening to the 'sync' event in my service worker file but NOTHING happens. Even my console.log does not fire

I ensure that i returned a promise in the waitUntil() function.

this is what my main.js file looks like

finalOrder.addEventListener('submit', function(event) { event.preventDefault(); var body = domArrayToObject(event.target) showForm(); if ('serviceWorker' in navigator && 'SyncManager' in window) { (navigator.serviceWorker.ready .then(worker => { return worker.sync.register('write-req') .then(function(s){ localStorage.setItem('req', JSON.stringify(body)); }).catch(err => console.log(err)) }).catch(err => console.log(err))) } else { sendMails(body); } }) 

this is my sendMails function (urlstring is a firebase function endpoint)

function sendMails(body) { return (Promise.all([fetch('urlstring', { method: 'POST', body: JSON.stringify(body), headers:{ 'Content-Type': 'application/json' } }) .then(res => res.json()) .then(response => console.log(res)) .catch(err => console.log(err)), fetch('urlstring', { method: 'POST', body: JSON.stringify(body), headers:{ 'Content-Type': 'application/json' } }) .then(res => res.json()) .then(response => console.log(res)) .catch(err => console.log(err))]).catch(err => console.log(err))) } 

this is my service worker file

self.addEventListener('sync', ev => { console.log('[Yaay Internet Connection]', ev) if (ev.tag == 'write-req') { console.log('[Service Worker] Syncing new Posts'); var body = localStorage.getItem('req'); ev.waitUntil(sendMails(body) .then((res) => { self.registration.showNotification('Order has been placed!!!', { body: 'Your Order has been placed. You will hear from us soon', image: '', icon: '', badge: '', actions: [ { action: 'add', title: 'add', icon: ''} ] }) })); } }) 

I want to listen to the 'sync' event and fire the callback. Sending the request to the endpoint if there is connection already or it is re established.

1
  • 1
    One thing to note is you can't use localStorage in service workers. Service workers only support async APIs. Commented Jun 13, 2019 at 14:38

1 Answer 1

0

Turns Out all i had to do was use indexedDB

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.