在Service Worker中侦听“同步”事件时未触发回叫

时间:2019-06-12 19:07:52

标签: javascript service-worker progressive-web-apps

我正在听我的服务工作者文件中的'sync'事件,但是什么也没有发生。甚至我的console.log都不会触发

我确保我在waitUntil()函数中返回了诺言。

这是我的main.js文件的样子

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);
    }
})

这是我的sendMails函数(URL字符串是Firebase函数的终结点)

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)))
}

这是我的服务人员文件

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: ''}
                ]
            })
        }));
    }
})

我想听'sync'事件并触发回调。如果已经建立连接或已建立连接,则将请求发送到端点。

1 个答案:

答案 0 :(得分:0)

原来我要做的就是使用indexedDB