Headless JS is a way to run tasks in JavaScript while your app is in the background. It can be used, for example, to sync fresh data, handle push notifications, or play music.
A task is a simple async function that you register on AppRegistry
, similar to registering React applications:
Then, in SomeTaskName.js
:
You can do anything in your task as long as it doesn't touch UI: network requests, timers and so on. Once your task completes (i.e. the promise is resolved), React Native will go into "paused" mode (unless there are other tasks running, or there is a foreground app).
Yes, this does still require some native code, but it's pretty thin. You need to extend HeadlessJsTaskService
and override getTaskConfig
, e.g.:
Now, whenever you start your service, e.g. as a periodic task or in response to some system event / broadcast, JS will spin up, run your task, then spin down.
BroadcastReceiver
, make sure to call HeadlessJsTaskService.acquireWakelockNow()
before returning from onReceive()
.You can edit the content above on GitHub and send us a pull request!