Application Preferences
How to work with the application preferences.
The prefs service provides a persistent key-value store for application preferences. Preferences are kept in an in-memory cache during the session and written to prefs.json in the application user data directory when you call persist().
Storing preferences
Use the typed setters to store a preference value under a string key. Keys can use dot-notation to express hierarchy, such as editor.fontSize or ui.sidebar.visible.
import { prefs } from '@mobrowser/api';
prefs.setString('ui.theme', 'dark')
prefs.setNumber('editor.fontSize', 14)
prefs.setBoolean('ui.sidebar.visible', true)
Empty keys and non-finite numbers (NaN, Infinity) are silently ignored.
Reading preferences
Use the typed getters to read a stored value. Each getter returns the type’s zero value ('', 0, or false) when the key is missing or holds a value of a different type.
const theme = prefs.getString('ui.theme')
const fontSize = prefs.getNumber('editor.fontSize')
const sidebarVisible = prefs.getBoolean('ui.sidebar.visible')
You can pass an optional default value that is returned instead of the zero value when the key is missing or has the wrong type:
const theme = prefs.getString('ui.theme', 'light')
const fontSize = prefs.getNumber('editor.fontSize', 14)
const sidebarVisible = prefs.getBoolean('ui.sidebar.visible', true)
Checking if a preference is set
Use the has* methods to test whether a key holds a value of the expected type before reading it. This is especially important for booleans, where the default return value of getBoolean (false) is also a valid stored value:
if (prefs.hasBoolean('ui.sidebar.visible')) {
const sidebarVisible = prefs.getBoolean('ui.sidebar.visible')
}
The same pattern applies to strings and numbers:
if (prefs.hasString('ui.theme')) {
const theme = prefs.getString('ui.theme')
}
if (prefs.hasNumber('editor.fontSize')) {
const fontSize = prefs.getNumber('editor.fontSize')
}
Removing preferences
To remove a single key from the in-memory cache, use remove():
prefs.remove('ui.theme')
To remove all keys at once, use clear():
prefs.clear()
Both operations affect only the in-memory cache. Call persist() afterwards to write the change to disk.
Persisting preferences
All reads and writes operate on an in-memory cache. Changes are not saved to disk automatically — if the application exits before persist() is called, any unsaved changes are lost.
Call persist() when you want to commit the current state of the cache to disk:
import { prefs } from '@mobrowser/api';
prefs.setString('ui.theme', 'dark')
prefs.setNumber('editor.fontSize', 14)
if (!prefs.persist()) {
console.error('Failed to save preferences')
}
persist() returns true if the preferences were saved successfully and false otherwise. It is good practice to check the return value and log or surface an error if saving fails.
Preferences are stored in prefs.json under the application user data directory.