关于Service Workers定期Ping服务器及Chrome周期性后台同步支持的问询
Hey there! Let's dive into your question about using Service Workers to send regular ping requests, and clarify the current state of Chrome's periodic background sync feature.
First off, the periodic background sync functionality you heard about back in 2015 is now a fully supported feature in Chrome (starting from version 80, released in February 2020). It was designed specifically for use cases like yours—periodic, user-authorized background tasks—while building in safeguards to prevent misuse (like the crypto mining scenario you noted).
Key Details & Implementation Steps
- User Authorization Required: To use this feature, your site must first request the
periodic-background-syncpermission from the user. This ensures users are aware that your site will run periodic background tasks. - Minimum Interval Limits: The shortest interval you can set is 15 minutes (configured via the
minIntervaloption when registering the sync). Keep in mind that Chrome may adjust this interval based on user behavior—for example, if a user rarely visits your site, the browser might lengthen the interval to conserve resources. - Site Interaction Requirement: Your site must have been interacted with by the user (e.g., they clicked a button, navigated through pages) before you can register a periodic sync. This prevents silent background activity from unused sites.
Example Code Snippets
Request Permission & Register Periodic Sync
In your main client-side code:// Check if periodic sync is supported if ('periodicSync' in navigator.serviceWorker) { // Request permission const permission = await navigator.permissions.query({ name: 'periodic-background-sync' }); if (permission.state === 'granted') { const registration = await navigator.serviceWorker.ready; // Register a sync that runs every 15 minutes (minimum allowed) await registration.periodicSync.register('ping-sync', { minInterval: 15 * 60 * 1000 // 15 minutes in milliseconds }); } }Handle the Sync in Service Worker
In your Service Worker file:self.addEventListener('periodicsync', (event) => { if (event.tag === 'ping-sync') { event.waitUntil( // Send your ping request to the server fetch('/api/ping', { method: 'POST' }) .then(response => { if (!response.ok) { throw new Error('Ping request failed'); } console.log('Ping sent successfully'); }) .catch(error => { console.error('Error sending ping:', error); }) ); } });
How It Differs from Regular Background Sync
Regular Background Sync is designed for one-off tasks that run when the user regains network connectivity. Periodic Background Sync, on the other hand, runs at specified intervals (even with an active network) as long as the user has granted permission and the site has been interacted with.
Checking Support
You can easily check if the user's Chrome version supports periodic background sync with the following check:
const isPeriodicSyncSupported = 'periodicSync' in navigator.serviceWorker;
So to wrap up: Yes, Chrome does support periodic background sync now, and it's perfectly suited for your regular ping request use case—just make sure to follow the permission and interaction requirements to stay within Chrome's guidelines.
内容的提问来源于stack exchange,提问作者dukitieneflow

