问题
service worker sync will not fire on case in android chrome WHAT IM MISSING ??? Same thing in here: JavaScript Background Sync Stops Working if Page is Loaded/Refreshed while offline
- unplug usb cable for development (for chrome dev tool)
- push android home button
- push power button for sleep (black screen)
- then i wait 5 minutes (at least)
- then i push power button for awake
- then i push myapp to wake app (app is not closed but set to sleep)
- then i blug in usb cable for debugging
- then i click some button to fire sync after that i see ---
in console "REGISTER" but "SYNC" event not fired if i click power button again (black screen) and then i click power button again - then it will wake up or i turn off wifi and then turn on wifi - then it will wake up
AND then is see in console "REGISTER" and "SYNC"
IF i wate 30 minutes then registered sync is deleted
CLIENT SIDE JS
var id = 'background-sync-' + (new Date()).getTime() + $.uniqid(6);
let postData = {
'type': 'background-sync',
'uuid': id,
};
registration.active.postMessage(postData);
SERVICE WORKER SIDE
self.addEventListener('message', function (event) {
//console.log('message=' + event.data.type);
if (event.data.type === 'background-sync') {
registerSync(event.data.uuid, event.data);
}
});
self.addEventListener('sync', function (event) {
console.log('SYNC');
//event.waitUntil(syncIt(event.tag));
});
function registerSync(uuid, data) {
if (data != undefined && data != null) {
let id = data.id;
//append data to storage
syncStore[id] = data;
//this is important
syncStore[id]['sending'] = false;
}
console.log('REGISTER');
//console.log(data);
//console.log(self.registration.sync.getTags());
self.registration.sync.register(uuid)
.then(function () {
})
.catch(function (err) {
return err;
});
}
回答1:
There no solution. Even background-periodic-sync does not work. So i have made work around - send regular post if possible and use background.sync as offline data sync. Problem is if i click power button once then sync request set to wait AND if second time then sync request will be sent to server.
solution code:
if( this.online ){
let self = this;
$.post(self.requestUrl, self.params, function (returnData) {
if( callback )
callback(returnData);
}).fail(function () {
window.backgroundSync(self.requestUrl, self.params, callback, self.storeData);
});
}
else {
window.backgroundSync(this.requestUrl, this.params, callback, this.storeData);
}
来源:https://stackoverflow.com/questions/65942049/javascript-background-sync-android-power-button