This is a reference of public JavaScript API of NuvolaKit, the core part of Nuvola Apps Runtime. Undocumented parts of the API are considered unstable, internal or experimental, so you should not use them.
Unlike C++ or Java, JavaScript doesn't have class-based inheritance, but prototype-based inheritance. New objects are created from other object that are prototypes and inheritance creates prototype chain. While some JavaScript frameworks try to simulate the class-based inheritance, NuvolaKit enforces usage of Object.create() method to create new objects from prototypes and provides two convenience wrappers: Nuvola.$prototype to create new prototype objects and Nuvola.$object to create new instance objects.
Most of the integration scripts will probably use only a small part of the API:
If you want to do more magic, you will need new spells:
Objects like Nuvola.menuBar, Nuvola.launcher, Nuvola.browser, Nuvola.mediaKeys are low-level components you probably don't want to use directly since Nuvola.MediaPlayer takes care about it.
Instance object of Actions prototype connected to Nuvola backend.
Instance object of Browser prototype connected to Nuvola backend.
Instance object of ConfigStorage prototype connected to Nuvola backend.
Instance object of Core prototype connected to Nuvola backend.
Global JavaScript Object
Note that only the web worker process has global window
object provided by a web browser engine.
The app runner process has bare global object.
Instance object of Launcher prototype connected to Nuvola backend.
Instance object of MediaKeys prototype connected to Nuvola backend.
Instance object of MenuBar prototype connected to Nuvola backend.
Instance object of SessionStorage prototype connected to Nuvola backend.
Convenience function to create new prototype object extending WebApp prototype.
Returns
new prototype object extending WebApp
var WebApp = Nuvola.$WebApp()
Creates new initialized object from prototype.
Creates new object that will have proto
as its prototype and will be initialized by calling
$init
method with provided arguments args
. This is similar to creating an instance object
from a class in class-based inheritance. Instance object names are in lowerCamelCase
.
Parameters
Object
$init
methodReturns
new initialized object
var house = Nuvola.$object(Building, 'King Street 1024, London') house.printAddress() var candyShop = Nuvola.$object(Shop, 'King Street 1024, London', 'candies') candyShop.printAddress() candyShop.printGoods()
Creates new object from prototype and mixins.
Creates new object that will have proto
as its prototype and will be extended with properties
from all specified mixins
. This is similar to creating a subclass in class-based inheritance.
See $object for instance object creation. Prototype object names are in UpperCamelCase
.
Parameters
Object
Returns
new prototype object
var Building = Nuvola.$prototype(null) Building.$init = function (address) { this.address = address } Building.printAddress = function () { console.log(this.address) } var Shop = Nuvola.$prototype(Building) Shop.$init = function (address, goods) { Building.$init.call(this, address) this.goods = goods } Shop.printGoods = function() { console.log(this.goods) }
Check sufficient Nuvola's version
Available since API 4.5
Parameters
Returns
true if Nuvola's version is greater than or equal to the required version
if (Nuvola.checkVersion && Nuvola.checkVersion(4, 5)) { // Safe to use API >= 4.5 }
Simulates click on element
Available since API 4.5: x, y coordinates were added.
Parameters
Encode version info as a single number
Available since API 4.5
Parameters
Returns
encoded version number
Download image and export it as base64 data-URI
Available since API 4.11
Parameters
Replaces placeholders in a template string with provided data.
Placeholders are in form of {n}
where n
is index of data argument starting at 1.
Special placeholders are {-1}
for {
and {-2}
for }
.
Parameters
Returns
String
alert(Nuvola.format('My name is {2}. {1} {2}!', 'James', 'Bond')) // 'My name is Bond. James Bond!' // You can create an alias var $fmt = Nuvola.format; alert($fmt('My name is {2}. {1} {2}!', 'James', 'Bond'))
Log message to terminal
Note: This function doesn't print to JavaScript console of WebKit Web Inspector, but to real console/terminal.
Parameters
Log exception to terminal
Available since Nuvola 4.8
Parameters
Creates HTML element
Parameters
Returns
new HTML element
Creates HTML text node
Parameters
Returns
new text node
Compares own properties of two objects
Parameters
Returns
Array of names of different properties
Parse time as number of microseconds
Parameters
Returns
the time in microseconds
Query element and return its attribute or null.
Available since API 4.11
Available since API 4.12: You can specify a parent element and a relative selector as an array of [parent element, selector].
Parameters
Returns
The attribute of the element, possibly modified with func, null if element is not found.
Query element and return text content or null.
Available since API 4.11
Available since API 4.12: You can specify a parent element and a relative selector as an array of [parent element, selector].
Parameters
Returns
Text content of the element, possibly modified with func, null if element is not found.
Simulates input and change event
Available since API 4.11
Available since API 4.12: The change event is emitted as well.
Parameters
Show infobar to user.
Asynchronous: This function returns a Promise object to resolve the value when it is ready. Read Using Promises to learn how to work with them.
Available since Nuvola 4.10
Parameters
Returns
true if a new info bar has been show, false if there already is an info bar with the same id.
Triggers mouse event on element
Available since API 4.5: x, y coordinates were added.
Parameters
Log warning to terminal
Note: This function doesn't print to JavaScript console of WebKit Web Inspector, but to real console/terminal.
Parameters
Manages actions
Actions can be shown in various user interface components such as menu, tray icon menu, Unity HUD, Unity Laucher Quicklist, or invoked by keyboard shortcut, remote control, etc.
Some actions are provided by the Nuvola Player backend (e. g. browser actions), some are created by JavaScript API objects (e. g. media player actions) and web app integration scripts can create custom actions with Actions.addAction or Actions.addRadioAction.
Initializes new Actions object
Activate (invoke) action
Parameters
Adds new simple or toggle action.
when action is activated, signal ActionActivated is emitted.
Parameters
dash-separated-lower-case
, e.g. toggle-play
Play
_Play
<ctrl>P
null
for simple actions, true
/false
for toggle actions (on/off)// Add new simple action ``play`` with icon ``media-playback-start`` Nuvola.actions.addAction('playback', 'win', 'play', 'Play', null, 'media-playback-start', null) // Add new toggle action ``thumbs-up`` with initial state ``true`` (on) Nuvola.actions.addAction('playback', 'win', 'thumbs-up', 'Thumbs up', null, null, null, true)
Adds new radio action (action with multiple states/option like old radios)
when action is activated, signal ActionActivated is emitted.
Parameters
dash-separated-lower-case
, e.g. toggle-play
options
array[stateId, label, mnemo_label, icon, keybinding]
. stateId
is unique identifier (Number or String), other parameters are described in addAction
method.// define rating options - 5 states with state id 0-5 representing 0-5 stars var ratingOptions = [ // stateId, label, mnemo_label, icon, keybinding [0, 'Rating: 0 stars', null, null, null, null], [1, 'Rating: 1 star', null, null, null, null], [2, 'Rating: 2 stars', null, null, null, null], [3, 'Rating: 3 stars', null, null, null, null], [4, 'Rating: 4 stars', null, null, null, null], [5, 'Rating: 5 stars', null, null, null, null] ] // Add new radio action named ``rating`` with initial state ``0`` (0 stars) Nuvola.actions.addRadioAction('playback', 'win', 'rating', 0, ratingOptions)
Bind HTML button to an action
The button.disabled and action.enabled properties are synchronized and action is activated when button is clicked.
Parameters
var navigateBack = Nuvola.makeElement('button', null, '<') var elm = document.getElementById('bar') elm.appendChild(navigateBack) Nuvola.actions.bindButton(navigateBack, Nuvola.BrowserAction.GO_BACK)
Get current state of toggle or radio actions.
Deprecated since Nuvola 4.8: Use async variant instead.
Parameters
Returns
current state: true/false
for toggle actions, one of stateId entries of radio actions
var thumbsUp = Nuvola.actions.getState('thumbs-up') console.log('Thumbs up is toggled ' + (thumbsUp ? 'on' : 'off')) var stars = Nuvola.actions.getState('rating') console.log('Number of stars: ' + stars)
Get current state of toggle or radio actions.
Asynchronous: This function returns a Promise object to resolve the value when it is ready. Read Using Promises to learn how to work with them.
Available since Nuvola 4.8
Parameters
Returns
current state: true/false
for toggle actions, one of stateId entries of radio actions
Nuvola.actions.getStateAsync('thumbs-up').then(function (state) { console.log('Thumbs up is toggled ' + (state ? 'on' : 'off')); }) Nuvola.actions.getStateAsync('rating').then(function (stars) { console.log('Number of stars: ' + stars) })
Checks whether action is enabled
Deprecated since Nuvola 4.8: Use async variant instead.
Parameters
Returns
true is action is enabled, false otherwise
Checks whether action is enabled
Asynchronous: This function returns a Promise object to resolve the value when it is ready. Read Using Promises to learn how to work with them.
Available since Nuvola 4.8
Parameters
Returns
true is action is enabled, false otherwise
Sets whether action is enabled
Note: consider use of method Actions.updateEnabledFlag that is more effective, because it performs caching of enabled flags and updates them only if necessary.
Parameters
Set current state of toggle or radio actions.
Note: consider use of method Actions.updateState that is more effective, because it performs caching of states and updates them only if necessary.
Parameters
true/false
for toggle actions, one of stateId entries of radio actions// toggle thumbs-up off Nuvola.actions.setState('thumbs-up', false) // Set 5 stars Nuvola.actions.setState('rating', 5)
Update action enabled flag
This method uses cache of action enabled flags to update them only if necessary.
Parameters
Bulk update of action enabled flags
This method uses cache of action enabled flags to update them only if necessary.
Parameters
action name
: enabled flag
Update of action state
This method uses cache of action states to update them only if necessary.
Parameters
true/false
for toggle actions, one of stateId entries of radio actionsBulk update of action states
This method uses cache of action states to update them only if necessary.
Parameters
action name
: state
Emitted when an action is activated.
Parameters
MyObject.$init = function () { Nuvola.actions.connect('ActionActivated', this) } MyObject._onActionActivated = function (emitter, name, param) { console.log('Action activated: ' + name) }
Emitted when an action has been enabled or disabled.
Parameters
MyObject.$init = function () { Nuvola.actions.connect('ActionEnabledChanged', this) } MyObject._ActionEnabledChanged = function (emitter, name, enabled) { console.log('Action ' + name + ' ' + (enabled ? 'enabled' : 'disabled') + '.') }
Prototype object for web browser management
Initializes new Browser object
Request download of a file
Parameters
callback will be called with two arguments:
result
object with propertiessuccess
- true
if the download has been successful, false
otherwisestatusCode
- a HTTP status codestatusText
- description of the HTTP status codefilePath
- filesystem path to the downloaded filefileURI
- URI of the downloaded file (file:///...
)data
- data argument passed to downloadFileAsyncPrototype object to access persistent configuration
Note: Use SessionStorage for temporary data.
Initializes new ConfigStorage object
Emitted when a configuration key is changed
Parameters
Prototype object to manage Nuvola Player Core
Initializes new Core instance object
Returns information about a component
Deprecated since Nuvola 4.8: Use async variant instead.
Parameters
Returns
Object component info
Returns information about a component
Asynchronous: This function returns a Promise object to resolve the value when it is ready. Read Using Promises to learn how to work with them.
Available since Nuvola 4.8
Parameters
Returns
Object component info
Returns whether a component is loaded and active
Deprecated since Nuvola 4.8: Use async variant instead.
Parameters
Returns
Boolean true if the component is active
Returns whether a component is loaded and active
Asynchronous: This function returns a Promise object to resolve the value when it is ready. Read Using Promises to learn how to work with them.
Available since Nuvola 4.8
Parameters
Returns
Boolean true if the component is active
Returns whether a component is loaded
Deprecated since Nuvola 4.8: Use async variant instead.
Parameters
Returns
Boolean true if the component is loaded
Returns whether a component is loaded
Asynchronous: This function returns a Promise object to resolve the value when it is ready. Read Using Promises to learn how to work with them.
Available since Nuvola 4.8
Parameters
Returns
Boolean true if the component is loaded
Activates or deactivates a component
The component must be loaded.
Parameters
Returns
Boolean true (since Nuvola 4.8)
Emitted when a component has been loaded.
Parameters
Emitted when a component has been unloaded.
Parameters
Emitted on request for home page URL.
See Web apps with a variable home page URL.
Parameters
var _onHomePageRequest = function (emitter, request) { request.url = "http://tiliado.eu" }
Emitted at start-up when initialization of the app runner process is needed. You can use it to perform own initialization routine.
Parameters
InitWebWorker initialize web worker process hook
This signal is emitted every time just before a web page is loaded in the main frame of the web view.
Parameters
InitWebWorkerHelper initialize web worker helper hook
This signal is emitted only once just before a web page is loaded in the main frame of the web view.
Parameters
Emitted at start-up when initialization form is being built.
Parameters
Emitted on request for the last visited URL.
Parameters
var _onLastPageRequest = function (emitter, result) { request.url = Nuvola.config.get("last_uri") || null }
Emitted on request for navigation to a new web page.
Available since API 4.12: You can overwrite `request.url` field to force redirect.
Parameters
false
when the request.url
should be opened in user's default web browservar _onNavigationRequest = function (emitter, request) { request.approved = isAddressAllowed(request.url) }
Emitted on request for web page settings.
Parameters
var _onPageSettings = function (emitter, request) { request.userAgent = ( request.url.startsWith("https://accounts.google.com/") || request.url.startsWith("https://accounts.youtube.com/") ? "WEBKIT" : null ) }
Emitted when preferences dialog is being built.
Parameters
Emitted on request to quit the application by closing the main window.
This signal is emitted in both App Runner and Web Worker processes.
Parameters
var _onQuitRequest = function (emitter, result) { if (Nuvola.config.get("myapp.run_in_background")) { result.approved = false } }
Emitted on request for loading a web resource.
Parameters
var _onResourceRequest = function (emitter, request) { request.url = request.url.replace("webcomponents.js", "webcomponents2.js") }
Emitted after approved navigation to a new page URL.
Parameters
var _onUriChanged = function(emitter, uri) { Nuvola.config.set("last_uri", uri) }
Prototype object to hold key-value mapping
Initializes new key-value storage
Parameters
Get value by key name
Note that behavior on a key without an assigned value nor the default value
is undefined - it may return anything or throw and error. (The current implementation returns string '<UNDEFINED>'
as it helps to identify unwanted manipulation with undefined
value type.)
Deprecated since Nuvola 4.8: Use async variant instead.
Parameters
Returns
value set by KeyValueStorage.set or KeyValueStorage.setDefault for given key
Get value by key name
Note that behavior on a key without an assigned value nor the default value
is undefined - it may return anything or throw and error. (The current implementation returns string '<UNDEFINED>'
as it helps to identify unwanted manipulation with undefined
value type.)
Asynchronous: This function returns a Promise object to resolve the value when it is ready. Read Using Promises to learn how to work with them.
Available since Nuvola 4.8
Parameters
Returns
value set by KeyValueStorage.set or KeyValueStorage.setDefault for given key
Check whether the storage has given key
Deprecated since Nuvola 4.8: Use async variant instead.
Parameters
Returns
false
if the storage doesn't contain value for the key (even if default value has been set), true
otherwise
Check whether the storage has given key
Asynchronous: This function returns a Promise object to resolve the value when it is ready. Read Using Promises to learn how to work with them.
Available since Nuvola 4.8
Parameters
Returns
false
if the storage doesn't contain value for the key (even if default value has been set), true
otherwise
Set value for given key
Deprecated since Nuvola 4.8: Use async variant instead.
Parameters
Set value for given key
Asynchronous: This function returns a Promise object to resolve the value when it is ready. Read Using Promises to learn how to work with them.
Available since Nuvola 4.8
Parameters
Set default value for given key
This function should be called only once per key, for example in Core::InitAppRunner handler.
Deprecated since Nuvola 4.8: Use async variant instead.
Parameters
WebApp._onInitAppRunner = function (emitter) { Nuvola.WebApp._onInitAppRunner.call(this, emitter) var ADDRESS = 'app.address' // Nuvola.config is a KeyValueStorage Nuvola.config.setDefault(ADDRESS, 'default') }
Set default value for given key
This function should be called only once per key, for example in Core::InitAppRunner handler.
Asynchronous: This function returns a Promise object to resolve the value when it is ready. Read Using Promises to learn how to work with them.
Available since Nuvola 4.8
Parameters
WebApp._onInitAppRunner = function(emitter) { Nuvola.WebApp._onInitAppRunner.call(this, emitter) var ADDRESS = 'app.address' // Nuvola.config is a KeyValueStorage Nuvola.config.setDefaultAsync(ADDRESS, 'default').catch(console.log.bind(console)) }
Manages launcher component (Unity dock item, tray icon, ...)
Add action to launcher's menu.
Parameters
Remove action from launcher's menu.
Parameters
Removes all launcher menu actions.
Set launcher menu actions.
This functionality has two implementations:
Parameters
Set launcher tooltip.
This functionality is currently implemented only by the tray icon.
Parameters
Prototype object integrating media keys handling
Media player controller.
Initializes media player
Add actions for media player capabilities
For example: star rating, thumbs up/down, like/love/unlike.
Actions that have been already added are ignored.
Parameters
Set whether it is possible to change volume
If the argument is same as in the previous call, this method does nothing.
Available since API 4.5
Parameters
Set whether it is possible to go to the next track
If the argument is same as in the previous call, this method does nothing.
Parameters
Set whether it is possible to go to the previous track
If the argument is same as in the previous call, this method does nothing.
Parameters
Set whether it is possible to pause playback
If the argument is same as in the previous call, this method does nothing.
Parameters
Set whether it is possible to start playback
If the argument is same as in the previous call, this method does nothing.
Parameters
Set whether it is possible to rate tracks
If rating is enabled, signal MediaPlayer::RatingSet is emitted. If the argument is same as in the previous call, this method does nothing.
Available since API 3.1
Parameters
Set whether it is possible to repeat a track or a playlist.
If the argument is same as in the previous call, this method does nothing.
Available since Nuvola 4.13
Parameters
Set whether it is possible to seek to a specific position of the track
If the argument is same as in the previous call, this method does nothing.
Available since API 4.5
Parameters
Set whether it is possible to shuffle playlist.
If the argument is same as in the previous call, this method does nothing.
Available since Nuvola 4.13
Parameters
Set current playback state
If the current state is same as the previous one, this method does nothing.
Parameters
Set the current repeat state.
If the current state is same as the previous one, this method does nothing.
Parameters
Set the current shuffle state.
If the argument is same as in the previous call, this method does nothing.
Available since Nuvola 4.13
Parameters
Set info about currently playing track.
If track info is same as in the previous call, this method does nothing.
Parameters
0.0
to 1.0
. This item is ignored prior API 3.1.HH:MM:SS.xxx
, e.g. 1:25.54
) or number of microseconds. This item is ignored prior API 4.5.Set current playback position
If the current position is the same as the previous one, this method does nothing.
Available since API 4.5
Parameters
HH:MM:SS.xxx
, e.g. 1:25.54
) or number of microseconds.Update current volume
If the current volume is the same as the previous one, this method does nothing.
Available since API 4.5
Parameters
Emitted when a rating is set.
Note that rating has to be enabled first with a method MediaPlayer.setCanRate.
Available since API 3.1
Parameters
0.0
to 1.0
.Prototype object for Menubar management
Adds new menu to the menubar or replaces existing menu with the same id
Parameters
Desktop notification.
Creates new named notification.
Parameters
Remove all actions available as buttons in notification.
Set actions available as buttons in notification.
Parameters
Shows notification.
Parameters
Update properties of a notification
Parameters
Manages desktop notifications.
Convenience method to creates new named notification.
Parameters
Check whether persistence is supported
Deprecated since Nuvola 4.8: Use async variant instead.
Returns
Boolean true if persistence is supported
Check whether persistence is supported
Asynchronous: This function returns a Promise object to resolve the value when it is ready. Read Using Promises to learn how to work with them.
Available since Nuvola 4.8
Returns
Boolean true if persistence is supported
Instantly show anonymous notification.
Parameters
Prototype object of a key-value storage with a lifetime limited to the current session
Note: Use SessionStorage to store persistent data.
Initializes new SessionStorage object.
Prototype object for web app integration.
Initializes new web app object.
Signal handler for Core::HomePageRequest
Signal handler for Core::InitAppRunner
Signal handler for Core::InitWebWorker. Override this method to integrate the web page.
WebApp._onInitWebWorker = function (emitter) { Nuvola.WebApp._onInitWebWorker.call(this, emitter) var state = document.readyState if (state === 'interactive' || state === 'complete') { this._onPageReady() } else { document.addEventListener('DOMContentLoaded', this._onPageReady.bind(this)) } } WebApp._onPageReady = function (event) { ... }
Signal handler for Core::InitWebWorkerHelper. Override this method to connect to Core::ResourceRequest signal.
Signal handler for Core::LastPageRequest
Signal handler for Core::NavigationRequest
Signal handler for Core::UriChanged
Convenience function to create new WebApp object linked to Nuvola API.
var WebApp = Nuvola.$WebApp() ... WebApp.start()
Translation functions.
These functions are only placeholders for now, but you can use them to mark translatable strings
and then check whether they are properly recognized by a tool xgettext
from the gettext
package.
See also translations documentation.
Translate string.
Placeholder: This function is only a placeholder for future functionality, but you can use it to mark translatable strings.
Usage notes
var _ = Nuvola.Translate.gettext
Parameters
Returns
String translated string
var _ = Nuvola.Translate.gettext /// You can use tree slashes to add comment for translators. /// It has to be on a line preceding the translated string though. console.log(_('Hello world!')) // Right var greeting = 'Hello world!' console.log(_(greeting)) // Wrong! var greeting = _('Hello world!') // Right console.log(greeting) var name = 'John' console.log(_('Hello ' + name + '!')) // Wrong! console.log(Nuvola.format(_('Hello {1}!'), name)) // Right
Translate string with support of singluar and plural forms.
Placeholder: This function is only a placeholder for future functionality, but you can use it to mark translatable strings.
Usage notes
var ngettext = Nuvola.Translate.ngettext
Parameters
Returns
String translated string
var ngettext = Nuvola.Translate.ngettext var eggs = 5 var text = ngettext( 'There is {1} egg in the fridge.', 'There are {1} eggs in the fridge.', eggs) console.log(Nuvola.format(text, eggs)) var text = ngettext( /// You can use tree slashes to add comment for translators. /// It has to be on a line preceding the singular string though. /// {1} will be replaced by number of eggs in both forms, /// but can be omitted as shown in singular form. 'There is one egg in the fridge.', 'There are {1} eggs in the fridge.', eggs)
Translate string with support of a disambiguating message context.
This is mainly useful for short strings which may need different translations, depending on the context in which they
are used. e.g.: pgettext('Navigation', 'Back')
vs pgettext('Body part', 'Back')
.
Placeholder: This function is only a placeholder for future functionality, but you can use it to mark translatable strings.
Usage notes
var C_ = Nuvola.Translate.pgettext
Parameters
Returns
String translated string
var C_ = Nuvola.Translate.pgettext /// You can use tree slashes to add comment for translators. /// It has to be on a line preceding the translated string though. console.log(C_('Navigation', 'Back')) console.log(C_('Body part', 'Back'))
Provides signaling functionality.
Adds new signal listeners can connect to
Parameters
BookStore.$init = function() { /** * Emitted when a book is added. * * @param Book book book that has been added */ this.addSignal('BookAdded') }
Connect handler to a signal
The first argument passed to the handler is the emitter object, i.e. object that has emitted the signal, other arguments should be specified at each signal's description.
Parameters
_onSignalName
Throws
Error if signal doesn't exist
Logger._onBookAdded = function(emitter, book) { console.log('New book: ' + book.title + '.') } Logger.$init = function() { bookStore.connect('BookAdded', this) // equivalent: bookStore.connect('BookAdded', this, '_onBookAdded') }
Disconnect handler from a signal
Parameters
_onSignalName
Throws
Error if signal doesn't exist
Emit a signal
Parameters
Throws
Error if signal doesn't exist
BookStore.addBook = function(book) { this.books.push(book) this.emit('book-added', book) }
Names on browser's actions
Identifiers of media keys
Media player playback states
Base media player actions
Available since Nuvola 4.13: `REPEAT` and `SHUFFLE` actions were added.
Media player repeat status
Available since Nuvola 4.13