Product
Introducing License Enforcement in Socket
Ensure open-source compliance with Socket’s License Enforcement Beta. Set up your License Policy and secure your software!
@capacitor/background-runner
Advanced tools
Background Runner provides an event-based standalone JavaScript environment for executing your Javascript code outside of the web view.
npm install @capacitor/background-runner
npx cap sync
Background Runner has support for various device APIs that require permission from the user prior to use.
On iOS you must enable the Background Modes capability.
Once added, you must enable the Background fetch
and Background processing
modes at a minimum to enable the ability to register and schedule your background tasks.
If you will be making use of Geolocation or Push Notifications, enable Location updates
or Remote notifications
respectively.
After enabling the Background Modes capability, add the following to your app's AppDelegate.swift
:
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// ....
BackgroundRunnerPlugin.registerBackgroundTask()
BackgroundRunnerPlugin.handleApplicationDidFinishLaunching(launchOptions: launchOptions)
// ....
return true
}
To allow the Background Runner to handle remote notifications, add the following:
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
// ....
BackgroundRunnerPlugin.dispatchEvent(event: "remoteNotification", eventArgs: userInfo) { result in
switch result {
case .success:
completionHandler(.newData)
case .failure:
completionHandler(.failed)
}
}
}
Apple requires privacy descriptions to be specified in Info.plist
for location information:
NSLocationAlwaysUsageDescription
(Privacy - Location Always Usage Description
)NSLocationWhenInUseUsageDescription
(Privacy - Location When In Use Usage Description
)Read about Configuring Info.plist
in the iOS Guide for more information on setting iOS permissions in Xcode
This API requires the following permissions be added to your AndroidManifest.xml
:
<!-- Geolocation API -->
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-feature android:name="android.hardware.location.gps" />
The first two permissions ask for location data, both fine and coarse, and the last line is optional but necessary if your app requires GPS to function. You may leave it out, though keep in mind that this may mean your app is installed on devices lacking GPS hardware.
Android 13 requires a permission check in order to send notifications. You are required to call checkPermissions()
and requestPermissions()
accordingly.
On Android 12 and older it won't show a prompt and will just return as granted.
Starting on Android 12, scheduled notifications won't be exact unless this permission is added to your AndroidManifest.xml
:
<uses-permission android:name="android.permission.SCHEDULE_EXACT_ALARM" />
Note that even if the permission is present, users can still disable exact notifications from the app settings.
Read about Setting Permissions in the Android Guide for more information on setting Android permissions.
Background Runner is an event based JavaScript environment that emits events to a javascript runner file that you designate in your capacitor.config.ts
file. If the runner finds a event handler corresponding to incoming event in your runner file, it will execute the event handler, then shutdown once details.completed()
is called (or if the OS force kills your process).
addEventListener("myCustomEvent", (details) => {
console.log("do something to update the system here");
details.completed();
});
addEventListener("myCustomEventWithReturnData", (details) => {
console.log("accepted this data: " + JSON.stringify(details.user));
const updatedUser = details.user;
updatedUser.firstName = updatedUser.firstName + " HELLO";
updatedUser.lastName = updatedUser.lastName + " WORLD";
details.completed(updatedUser);
});
addEventListener("remoteNotification", (details) => {
console.log("received silent push notification");
CapacitorNotifications.schedule([
{
id: 100,
title: "Enterprise Background Runner",
body: "Received silent push notification",
},
]);
details.completed();
});
Calling details.completed()
is required within every event handler called by the runner. Failure to do this could result in your runner being killed by the OS if your event is called while the app is in the background. If the app is in the foreground, async calls to dispatchEvent
may not resolve.
On load, Background Runner will automatically register a background task that will be scheduled and ran once your app is backgrounded. The settings for this behavior is defined in your capacitor.config.ts
file:
const config: CapacitorConfig = {
plugins: {
BackgroundRunner: {
label: "com.example.background.task",
src: "background.js",
event: "myCustomEvent",
repeat: true,
interval: 2,
autoStart: false,
},
},
}
Background Runner does not execute your Javascript code in a browser or web view, therefore the typical Web APIs you may be used to may not be available. This includes DOM APIs nor ability to interact with your application's DOM.
Below is a list of the available Web APIs provided in Background Runner:
info
, log
, warn
, error
, and debug
are availabledecode
is availableencode
is availableuseCapture
not supportedmethod
, headers
and body
supported in options objectIn addition to the standard Web APIs, Background Runner also supports a number of custom APIs that expose relevant mobile device functionality:
get(key: string): string
set(key: string, value: string)
remove(key: string)
schedule()
getBatteryStatus()
getNetworkStatus()
getCurrentPosition()
Currently, the runners are designed for performing periodic bursts of work while your app is in the background, or for executing asynchronous work in a separate thread from your UI while your app is in the foreground. As a result, runners are not long lived. State is not maintained between calls to events in the runner. Each call to dispatchEvent()
creates a new context in with your runner code is loaded and executed, and once completed()
is called, the context is destroyed.
It’s not possible to run persistent, always running background services on mobile operating systems. Due to the limitations imposed by iOS and Android designed to reduce battery and data consumption, background tasks are constrained with various limitations that you must keep in mind while designing and implementing your background task.
completed()
or your task is killed.checkPermissions() => any
Check permissions for the various Capacitor device APIs.
Returns: any
Since: 1.0.0
requestPermissions(options: RequestPermissionOptions) => any
Request permission to display local notifications.
Param | Type |
---|---|
options | RequestPermissionOptions |
Returns: any
Since: 1.0.0
dispatchEvent(options: DispatchEventOptions) => any
Dispatches an event to the configured runner.
Param | Type |
---|---|
options | DispatchEventOptions |
Returns: any
Since: 1.0.0
Prop | Type |
---|---|
geolocation | PermissionState |
notifications | PermissionState |
Prop | Type |
---|---|
apis | {} |
Prop | Type | Description | Since |
---|---|---|---|
label | string | The runner label to dispatch the event to | 1.0.0 |
event | string | The name of the registered event listener. | 1.0.0 |
details | { [key: string]: any; } |
'prompt' | 'prompt-with-rationale' | 'granted' | 'denied'
'geolocation' | 'notifications'
FAQs
Capacitor Background Runner
The npm package @capacitor/background-runner receives a total of 611 weekly downloads. As such, @capacitor/background-runner popularity was classified as not popular.
We found that @capacitor/background-runner demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 0 open source maintainers collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Product
Ensure open-source compliance with Socket’s License Enforcement Beta. Set up your License Policy and secure your software!
Product
We're launching a new set of license analysis and compliance features for analyzing, managing, and complying with licenses across a range of supported languages and ecosystems.
Product
We're excited to introduce Socket Optimize, a powerful CLI command to secure open source dependencies with tested, optimized package overrides.