The Background Sync API allows you to send requests even when offline. The requests are queued and sent when the user comes back online.
With the configuration below, all requests starting with /form will be queued and sent when the user comes back online.
The queue name should be unique.
The method used to send the requests can be changed. This can be useful e.g. to separate POST and PUT requests with different retention times.
pwa:
serviceworker:
enabled: true
workbox:
enabled: true
background_sync:
- queue_name: 'form'
match_callback: 'startsWith: /form'
method: POST
max_retention_time: 7_200 # 5 days in minutes
force_sync_fallback: true #Optional
broadcast_channel: 'form-list'
Then in your templates, you can use the Stimulus Controller @pwa/backgroundsync-form that will manage the request for you.
<form {{ stimulus_controller('@pwa/backgroundsync-form') }} method="post">
...
<button {{ stimulus_action('@pwa/backgroundsync-form', 'send')}} type="submit">
Send!
</button>
</form>
When the broadcast channel is set, the number of requests in the queue can be known: an event is sent.
Also, the queue can be replayed on-demand.
The channel shall be the same as the one used in the configuration.
Please go offline and send a message. You will see that the message is placed in a queue. It will be sent when you come back online.