Skip to content

Storage

In this example we will show you how you can use the Storage API to save and/or share data across different Custom User Interfaces. One very common usage of this is, for example, to share data between Template UIs and Show UIs.

Client Side Storage

There are 3 types of storage methods that reside on the client (not the server), and are therefore only available locally to the specific client.

Tip

If you need to share data across different clients please use the Global Variables

  1. globalStorage - Data stored in the globalStorage is available to all user interfaces on the specific client, and it survives a page refresh and a restart of Studio.
  2. localStorage - Data stored in the localStorage is only accessible to the specific user interface, and it survives a page refresh and a restart of Studio.
  3. sessionStorage - Data stored in the sessionStorage is available to all user interfaces on the specific client, similar to globalStorage, however it is cleared when the Studio window/tab is closed. It survives a page refresh and is unaffected by a server restart.

Warning

Storage values must be strings. setItem silently ignores a non-string value - nothing is stored and no error is raised. This is why the JSON example below stringifies the data before storing it.

Example commands:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
// Store data in storage:
globalStorage.setItem('My Global Key', 'Some global value');
localStorage.setItem('My Local Key', 'Some local value');
sessionStorage.setItem('My Session Key', 'Some session value');

// Retrieve the data from storage
// Returned value will be undefined if the key does not exist
const globalData = globalStorage.getItem('My Global Key');
const localData = localStorage.getItem('My Local Key');
const sessionData = sessionStorage.getItem('My Session Key');

Info

Unlike the browser Storage API, getItem returns undefined - not null - for a key that was never set. key(index) likewise returns undefined when the index is out of range.

You can also store JSON data in each of the storage methods, however you will need to stringify and parse the data as follows:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
// Store data in storage:
// We stringify the JSON data when storing
globalStorage.setItem('My Global Key', JSON.stringify({ myData: 'Some Global Data' }));
localStorage.setItem('My Local Key', JSON.stringify({ myData: 'Some Local Data' }));
sessionStorage.setItem('My Session Key', JSON.stringify({ myData: 'Some Session Data' }));

// Retrieve the data from storage
// We parse the JSON String when retrieving
const globalData = JSON.parse(globalStorage.getItem('My Global Key'));
const localData = JSON.parse(localStorage.getItem('My Local Key'));
const sessionData = JSON.parse(sessionStorage.getItem('My Session Key'));

Removing data and reacting to changes

Every client side storage object also exposes:

Method Description
removeItem(key) Removes a single key.
clear() Removes every key in that storage.
on(key, callback) Calls callback with { key, value } every time that key changes, including changes made by another user interface on the same client.
once(key, callback) The same, but the callback is called only for the first change.
off(key, callback) Removes a subscription.
1
2
3
4
5
6
// React to a value another user interface stored
globalStorage.on('My Global Key', e => console.log('changed', e.key, e.value));

// Remove a single key, or everything in this storage
globalStorage.removeItem('My Global Key');
globalStorage.clear();

Page Storage

The fourth storage scope is the page storage, Api.page.storage. It is not a client side store: the data is kept with the Page, so it is saved to the database when the operator saves the page and is then available to every client that opens that page. See the Page storage API for the full reference.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
// Store a single value, or several values at once
Api.page.storage.set('myKey', 'My Value');
Api.page.storage.set({ myKey: 'My Value', myOtherKey: 42 });

// Retrieve a value, list the keys, or read the whole object
const value = Api.page.storage.get('myKey');
const keys = Api.page.storage.keys();
const all = Api.page.storage.value;

// Remove a single key, or everything
Api.page.storage.remove('myKey');
Api.page.storage.clear();

Unlike the client side storages, page storage accepts any JSON-serialisable value, so numbers and objects do not have to be stringified. A value containing a circular reference throws.

Warning

Writing to Api.page.storage does not mark the page as modified. If the operator navigates away without saving the page for another reason, the stored data is discarded without a prompt. Make sure the page is saved after you write to it, for example with Api.page.save().

Global Variables

Global Variables are saved on the server side and are consistent, meaning that they can be accessed by all clients connected to the server. The data stored can be any valid JS value (string / boolean / number / object / ...)

Tip

Global variable API is promise based as it requires communication with the server

Warning

Global Variable keys are trimmed and lower-cased, so "MyKey", "mykey" and " MyKey " all refer to the same variable.

Example command:

1
2
3
4
5
6
7
8
9
 try {
    // Use promise to set Global Varaible Value
    await GlobalVariables.set("MyKey", "My Global Variable Value")
    // Use promise to retrieve Global Varaible Value
    const myVariable = await GlobalVariables.get("MyKey");
    console.log(myVariable);
  } catch (err) {
    console.error("Oops something went wrong ", err);
  }

Info

get resolves to null and set resolves to false when the server call fails - neither of them rejects, so the catch block above is a safety net rather than the normal error path. Check the resolved value if you need to know whether the call succeeded.

Besides get and set, the Global Variables API offers:

Method Description
exists(key) Resolves to whether the variable exists on the server.
remove(key) Deletes the variable.
keys() Resolves to the list of global variable names.
on(key, callback) / once / off Calls callback with { key, value } whenever that variable is added, updated or removed on the server, from any client.
subscribe(key?) / unsubscribe(key?) Additionally raises the onGlobalVariable... script events (for example onGlobalVariableUpdated) for that key. Called without a key, it applies to every variable. Not needed for on.
1
2
// Runs whenever any client changes this global variable
GlobalVariables.on('MyKey', e => console.log('changed', e.key, e.value));

Info

The Storage API is derived from the official MDN Storage API

Get All Stored Keys

We can retrieve all the stored keys in any of the client side storage methods with the following code example:

1
2
3
4
for (let i = 0; i < localStorage.length; i++) {
  const key = localStorage.key(i);
  console.log(key, localStorage.getItem(key));
}

For page storage, use Api.page.storage.keys().

Example Files

This Example UI shows how you can store and retrieve data using all 4 storage methods. API Request}

Download ezUI File