I'm new to service workers and I have the following scenario:
Here is a chunk from my script.js:
if ('serviceWorker' in navigator) {
if (navigator.serviceWorker.controller) {
var msg = {
'form_data': params
}
navigator.serviceWorker.controller.postMessage(msg);
}
}
$.post(url, params, function (data) {
}).done(function(data) {
console.log('succ');
}).fail(function() {
console.log('fail');
});
Here is a chunk from my service-worker.js:
self.addEventListener('fetch', e => {
const reqClone = e.request.clone();
if (reqClone.method === 'POST') {
e.respondWith(fetch(reqClone).catch(function(error) {
savePostRequests(reqClone.url, form_data)
//Function to add requests to IndexedDB
}))
}
});
self.addEventListener('message', function (e) {
if (e.data.hasOwnProperty('form_data')) {
form_data = e.data.form_data;
}
});
While in Chrome the message event gets fired before the fetch event, meaning I'm getting my form_data in the fetch, in Safari the message event gets fired after the fetch event, so I'm not getting the form_data.
I need the POST call parameters in the fetch event to store them in the IndexedDB when I'm offline.
What am I doing wrong? Is there a different way to handle this?
Any help would be appreciated.