Skip to content

Application ​

Application represents the running app. Its only instance is the global object application: the runtime creates it when the app launches, there is exactly one per app, and it lives until the app ends. Any part of a script can use it directly; you don't create it, and you can't create another one.

application handles app-wide concerns:

  • App information: bundle ID, version, and the contents of the configuration file.
  • App state: whether the app is in the foreground or background, and which scenes currently exist.
  • App-level events: the UI can be built, the app entered the background, memory is low, the app was opened by a link, there is an unhandled exception.
  • App-level capabilities: entry points to local storage, files, and network status, asking the system to open a URL (opening outward; another app opening this app is the event in the previous item), and asking the system for extra time when moving to the background. With @nacrejs/keychain installed, the keychain entry point is here too; with @nacrejs/push installed, so is the remote notifications entry point.
  • Native module entry point: methods provided by the app's own native code and third-party native SDKs are called from application.nativeModules.

The UI is not on application. The UI belongs to scenes (UIWindowScene): a scene represents one instance of the app's UI, the system creates it, and a window must be created on a scene to be displayed. application fires sceneconnect when a scene becomes available and keeps track of the current scenes.

The runtime also provides several event-related classes, each with its own page: EventTarget (the base class for objects that fire events), Event (the base class for event objects), and the event objects for three of the events on application: ErrorEvent, PromiseRejectionEvent, and OpenURLEvent.

Inheritance: EventTarget → Application

For how to organize startup code and handle foreground, background, and memory warnings, see the guide Handling the app lifecycle; for handling errors in one place, see Handling errors in one place; for handling links that open the app, see Handling links that open the app.

Constructor ​

It can't be created with new. new Application() throws TypeError: Illegal constructor. Use the global application directly.

Instance properties ​

App information. These four properties don't change while the app runs, so they have no change events:

PropertyDescription
info read-onlyThe full contents of Info.plist
bundleIdentifier read-onlyBundle ID
version read-onlyUser-facing version number
build read-onlyBuild number

App state:

PropertyDescription
state read-onlyThe foreground/background state of all scenes combined
scenes read-onlyThe currently connected scenes
supportsMultipleScenes read-onlyWhether multiple scenes can exist at the same time
protectedDataAvailable read-onlyWhether encrypted, protected files can be read right now
backgroundTimeRemaining read-onlyHow many more seconds the app can run in the background. Infinity in the foreground

Device environment settings:

PropertyDescription
layoutDirection read-onlyThe writing direction of the UI
contentSizeCategory read-onlyThe text size level the user chose
backgroundRefreshStatus read-onlyWhether the app can refresh content in the background
prefersReducedResourceUsage read-onlyWhether the system recommends that the app reduce resource usage
idleTimerDisabledWhether automatic screen locking is prevented

Capability entry points. Each read returns the same object:

PropertyDescription
storage read-onlyKey-value storage
fileSystem read-onlyFile reading and writing
network read-onlyNetwork status: whether connected, which kind of network, whether metered
keychain read-onlyEncrypted storage for tokens and passwords. Only present in projects that install @nacrejs/keychain
remoteNotifications read-onlyRemote notifications: registration, the device token, silent pushes. Only present in projects that install @nacrejs/push
nativeModules read-onlyNative modules registered in this app

Instance methods ​

Also inherits addEventListener(), removeEventListener(), and dispatchEvent() from EventTarget.

MethodDescription
openURL()Hands a URL to the system to open
runBackgroundTask()Runs a function and, if the app moves to the background meanwhile, asks the system for extra time to finish it

Events ​

Event names are all lowercase, with no separators.

Scenes:

EventWhen it fires
sceneconnectThe system has created a scene. Put UI code here
scenedisconnectThe system destroyed a scene

Links:

EventWhen it fires
openurlAnother app or a link opened this app

Foreground and background:

EventWhen it fires
inactiveThe app is about to leave the active state
backgroundThe app has entered the background
foregroundThe app is about to return to the foreground
activeThe app has entered the active state
beforeterminateThe system is about to terminate the app

System notifications:

EventWhen it fires
memorywarningThe system is low on memory, and the app should release caches
screenshotThe user took a screenshot
significanttimechangeThe time changed significantly: midnight passed, the time zone changed, daylight saving time switched
contentsizecategorychangeThe user changed the system text size
localechangeThe user changed the region settings: country or region, currency, number and date formats
protecteddataavailableThe device was unlocked, and encrypted, protected files can be read
protecteddataunavailableThe device is about to lock, and encrypted, protected files will become unreadable
backgroundrefreshstatuschangeThe user changed the background refresh setting
reducedresourceusagechangeThe system's recommendation on resource usage changed

Errors:

EventWhen it fires
errorThere is an uncaught exception
unhandledrejectionA Promise was rejected without a handler attached

application can also listen for and dispatch events you define yourself. The event name can be any string, as long as it differs from the ones above.

Scenes ​

There are two ways to get a scene:

SourceWhen it has a value
e.scene of the sceneconnect eventWhen the event fires
application.scenesAfter sceneconnect fires. It's an empty array when the script starts running

So the entry point for UI code is always sceneconnect. After the app launches, the runtime first runs all of main.js, and only then does the system create the scene. When a scene is destroyed, scenedisconnect fires and the scene is removed from application.scenes at the same time.

How application and scenes divide the work:

Responsible for
applicationThe whole app: information, the foreground/background state of all scenes combined, memory warnings, errors
SceneOne UI instance: its windows and its own foreground/background state

Foreground, background, and run state ​

An iOS app doesn't run all the time. When the user goes back to the Home Screen or switches to another app, the current app enters the background, and the system may then suspend it or terminate it outright.

application.state has three normal values:

ValueMeaning
'active'In the foreground and receiving user input
'inactive'In the foreground but temporarily not receiving input. For example, while switching apps, during an incoming call, or with Notification Center pulled down
'background'Not on screen. This is also the value when the script starts running

Four events fire when the state changes. Two of them fire before the state changes:

EventMeaningValue of state when the event arrives
inactiveAbout to leave the active state'active', still the old value
backgroundHas entered the background'background'
foregroundAbout to return to the foreground'background', still the old value
activeHas entered the active state'active'

Scenes also have four events with the same names. The ones on application reflect the state of all scenes combined; the ones on a scene reflect that one scene's state. The values read from the two can differ at the same moment; see UIWindowScene.

After the app enters the background, the system suspends it after a short while. Wrap work that has already started and needs a few more seconds to finish (an upload, writing a file) in runBackgroundTask(), and the system gives it extra time to finish; read how many seconds are left from backgroundTimeRemaining.

System events can't be canceled ​

Events on application fall into two categories, which differ in whether preventDefault() works:

CategoryIncludescancelablepreventDefault()
System notificationssceneconnect, openurl, the foreground/background events, memorywarning, and so on: everything except the two belowfalseHas no effect and doesn't throw
Error eventserror, unhandledrejectiontruePrevents the runtime from printing the default error log

System notifications can't be canceled because listeners don't run at the moment the system sends the notification. The runtime dispatches them later, when the system has already finished handling them. See How the runtime works. The target of every system notification is application.

Unhandled exceptions don't terminate the app ​

When an exception thrown in JS isn't caught by try / catch, the app doesn't exit. The code that threw stops running; everything else keeps working: listeners stay registered, timers keep firing, and the UI stays usable.

Where the exception occursHow the runtime handles it
Top level of main.js, timer callbacks, event listener callbacks (including the sceneconnect callback and button tap callbacks)Fires error on application. If no listener cancels it, prints an error log starting with Uncaught to the console
A Promise is rejected with no handler attached. Exceptions thrown in async functions fall into this categoryFires unhandledrejection on application. If no listener cancels it, prints an error log starting with Uncaught (in promise)
  • When the top level of main.js throws, the top-level code after that line doesn't run. Listeners registered before it remain in effect.
  • When an event listener throws, the other listeners for the same event still run, and error fires before the next listener runs.
  • Calling preventDefault() in a listener for either event cancels only the default log the runtime prints. The exception has already happened, and the interrupted code doesn't resume.

Examples ​

The starting point of every app ​

Print the app's information, then create the window and view controller once the system is ready.

js
console.log('Bundle ID', application.bundleIdentifier);
console.log('Version', application.version, 'Build', application.build);
console.log('Scene count', application.scenes.length);

application.addEventListener('sceneconnect', (e) => {
  const win = new UIWindow(e.scene);
  const page = new UIViewController();
  page.view.backgroundColor = 'systemBackground';
  win.rootViewController = page;
  win.makeKeyAndVisible();

  console.log('UI ready, scene count', application.scenes.length);
});

Effect

  • The console first prints three lines. For an app whose bundle ID is com.example.shop:
    • Bundle ID com.example.shop
    • Version 0.1.0 Build 1
    • Scene count 0
  • The screen then changes from black to the system background color: white in light mode, black in dark mode.
  • The console prints UI ready, scene count 1.

This code hasn't been run as a whole in the simulator. Every API it uses has been run in the acceptance tests.

Corresponding iOS API ​

application isn't an item-by-item mapping of UIApplication. It gathers app-level capabilities that iOS spreads across several places onto one object.

ObjCJS
NSBundle.mainBundle.infoDictionaryapplication.info
NSBundle.mainBundle.bundleIdentifierapplication.bundleIdentifier
UIApplication.sharedApplication.applicationStateapplication.state
UIApplication.sharedApplication.connectedScenesapplication.scenes
UIApplication.sharedApplication.supportsMultipleScenesapplication.supportsMultipleScenes
UIApplication.sharedApplication.userInterfaceLayoutDirectionapplication.layoutDirection
UIApplication.sharedApplication.preferredContentSizeCategoryapplication.contentSizeCategory
UIApplication.sharedApplication.backgroundRefreshStatusapplication.backgroundRefreshStatus
UIApplication.sharedApplication.protectedDataAvailableapplication.protectedDataAvailable
UIApplication.sharedApplication.idleTimerDisabled = YESapplication.idleTimerDisabled = true
[UIApplication.sharedApplication openURL:url options:@{} completionHandler:…]application.openURL(url)
beginBackgroundTaskWithName:expirationHandler:, endBackgroundTask:application.runBackgroundTask(work, { name })
UIApplication.sharedApplication.backgroundTimeRemainingapplication.backgroundTimeRemaining
NSUserDefaults.standardUserDefaultsapplication.storage
UISceneWillConnectNotificationapplication.addEventListener('sceneconnect', …)
UISceneDidDisconnectNotificationapplication.addEventListener('scenedisconnect', …)
scene:openURLContexts:application.addEventListener('openurl', …)
scene:continueUserActivity: with activity type NSUserActivityTypeBrowsingWebapplication.addEventListener('openurl', …)
URLContexts and userActivities of connectionOptions in scene:willConnectToSession:options:The same openurl, fired after sceneconnect
CFBundleURLTypes in Info.plistios.urlSchemes in nacre.config.json
UIApplicationDidBecomeActiveNotificationapplication.addEventListener('active', …)
UIApplicationWillResignActiveNotificationapplication.addEventListener('inactive', …)
UIApplicationDidEnterBackgroundNotificationapplication.addEventListener('background', …)
UIApplicationWillEnterForegroundNotificationapplication.addEventListener('foreground', …)
UIApplicationDidReceiveMemoryWarningNotificationapplication.addEventListener('memorywarning', …)
UIApplicationUserDidTakeScreenshotNotificationapplication.addEventListener('screenshot', …)
UIApplicationSignificantTimeChangeNotificationapplication.addEventListener('significanttimechange', …)
UIContentSizeCategoryDidChangeNotificationapplication.addEventListener('contentsizecategorychange', …)
NSCurrentLocaleDidChangeNotificationapplication.addEventListener('localechange', …)
UIApplicationProtectedDataDidBecomeAvailableapplication.addEventListener('protecteddataavailable', …)
UIApplicationProtectedDataWillBecomeUnavailableapplication.addEventListener('protecteddataunavailable', …)
UIApplicationBackgroundRefreshStatusDidChangeNotificationapplication.addEventListener('backgroundrefreshstatuschange', …)
UIApplicationWillTerminateNotificationapplication.addEventListener('beforeterminate', …)

Comparison with the browser ​

BrowserNacre
window.addEventListener('error', …)application.addEventListener('error', …)
window.addEventListener('unhandledrejection', …)application.addEventListener('unhandledrejection', …)
document.visibilityState and visibilitychangeapplication.state and the four foreground/background events
navigator.wakeLock.request('screen')application.idleTimerDisabled = true
rejectionhandled eventNone

See also ​