Export (0) Print
Expand All

Persisting app state and settings

apps for Office

Understand the options for persisting app state and settings data for content, task pane, and mail apps. Learn about the common features and differences between the Settings, RoamingSettings, and CustomProperties objects of the JavaScript API for Office for persisting app state, and see examples of how to use them.

Last modified: November 14, 2014

Applies to: Access app for SharePoint | Excel 2013 | Excel 2013 RT | Excel 2013 SP1 | Excel Online | Outlook 2013 | Outlook 2013 RT | Outlook 2013 SP1 | Outlook for Mac for Office 365 | Outlook Web App | OWA for Devices | PowerPoint 2013 | PowerPoint 2013 RT | PowerPoint 2013 SP1 | PowerPoint Online | Project 2013 | Project 2013 SP1 | Word 2013 | Word 2013 RT | Word 2013 SP1

In this article
Persisting app state and settings with the JavaScript API for Office
Settings data is managed in memory at runtime
How to save app state and settings per document for content and task pane apps
How to save settings in the user's mailbox for mail apps as roaming settings
How to save settings per item for mail apps as custom properties
Additional resources

   Office.js: v1.0, v1.1

   Apps for Office manifests schema: v1.0, v1.1

Note Note

"Outlook" in this article refers to Outlook for Windows, Outlook for Mac, Outlook RT, OWA for Devices (OWA for Android phones, OWA for iPad, OWA for iPhone), and Outlook Web App. At this point, Outlook for Mac supports JavaScript API for Office in only Outlook read mode, and can activate mail apps that reference office.js version 1.0 or 1.1 and use apps for Office schema version 1.0.

Apps for Office are essentially web applications running in the stateless environment of a browser control. As a result, your app may need to persist data to maintain the continuity of certain operations or features across sessions of using your app. For example, your app may have custom settings or other values that it needs to save and reload the next time it's initialized, such as a user's preferred view or default location.

To do that, you can:

  • Use members of the JavaScript API for Office that store data as name/value pairs in a property bag stored in a location that depends on app type.

  • Use techniques provided by the underlying browser control: browser cookies, or HTML5 web storage (localStorage or sessionStorage).

This article focuses on how to use the JavaScript API for Office to persist app state. For examples of using browser cookies and web storage, see the Persist custom settings code sample.

Persisting app state and settings with the JavaScript API for Office
Settings data is managed in memory at runtime
How to save app state and settings per document for content and task pane apps
How to save settings in the user's mailbox for mail apps as roaming settings
How to save settings per item for mail apps as custom properties
Additional resources

The JavaScript API for Office provides the Settings, RoamingSettings, and CustomProperties objects for saving app state across sessions as described in the following table. In all cases, the saved settings values are associated only with the Id of the app that created them, and can't be accessed by other apps.

Object

App type support

Storage location

Office host support

Settings

content and task pane

The document, spreadsheet, or presentation the app is working with.

Content and task pane app settings are available only to the app that created them, and only from the document where they are saved.

Word 2013, Excel 2013, Excel Online, or PowerPoint 2013.

Note: Task pane apps for Project 2013 don't support the Settings API for storing app state or settings. However, for apps running in Project (as well as other Office host applications) you can use techniques such as browser cookies or web storage. For more information on these techniques, see the Persist custom settings code sample.

RoamingSettings

mail

The user's Exchange server mailbox where the app is installed.

Because these settings are stored in the user's server mailbox, they can "roam" with the user and are available to the app when it is running in the context of any supported client host application or browser accessing that user's mailbox.

Mail app roaming settings are available only to the app that created them, and only from the mailbox where the app is installed.

Outlook

CustomProperties

mail

The message, appointment, or meeting request item the app is working with.

Mail app item custom properties are available only to the app that created them, and only from the item where they are saved.

Outlook

Internally, the data in the property bag accessed with the Settings, CustomProperties, or RoamingSettings objects is stored as a serialized JavaScript Object Notation (JSON) object that contains name/value pairs. The name (key) for each value must be a string, and the stored value can be a JavaScript string, number, date, or object, but not a function.

This example of the property bag structure contains three defined string values named firstName, location, and defaultView.

{
"firstName":"Erik",
"location":"98052",
"defaultView":"basic"
}

After the settings property bag is saved during the previous app session, it can be loaded when the app is initialized or at any point after that during the app's current session. During the session, the settings are managed in entirely in memory using the get, set, and remove methods of the object that corresponds to the kind settings you are creating (Settings, CustomProperties, or RoamingSettings).

Important noteImportant

To persist any additions, updates, or deletions made during the app's current session to the storage location, you must call the saveAsync method of the corresponding object used to work with that kind of settings. The get, set, and remove methods operate only on the in-memory copy of the settings property bag. If your app is closed without calling saveAsync, any changes made to settings during that session will be lost.

To persist state or custom settings of a content or task pane app for Word, Excel, or PowerPoint, you use the Settings object and its methods. The property bag created with the methods of the Settings object are available only to the instance of the content or task pane app that created it, and only from the document in which it is saved.

The Settings object is automatically loaded as part of the Document object, and is available when the task pane or content app is activated. After the Document object is instantiated, you can access the Settings object with the settings property of the Document object. During the lifetime of the session, you can just use the Settings.get, Settings.set, and Settings.remove methods to read, write, or remove persisted settings and app state from the in-memory copy of the property bag.

Because the set and remove methods operate against only the in-memory copy of the settings property bag, to save new or changed settings back to the document the app is associated with you must call the Settings.saveAsync method.

Creating or updating a setting value

The following code example shows how to use the Settings.set method to create a setting called 'themeColor' with a value 'green'. The first parameter of the set method is the case-sensitive name (Id) of the setting to set or create. The second parameter is the value of the setting.

Office.context.document.settings.set('themeColor', 'green');

The setting with the specified name is created if it doesn't already exist, or its value is updated if it does exist. Use the Settings.saveAsync method to persist the new or updated settings to the document.

Getting the value of a setting

The following example shows how use the Settings.get method to get the value of a setting called "themeColor". The only parameter of the get method is the case-sensitive name of the setting.

write('Current value for mySetting: ' + Office.context.document.settings.get('themeColor'));

// Function that writes to a div with id='message' on the page.
function write(message){
    document.getElementById('message').innerText += message; 
}

The get method returns the value that was previously saved for the setting name that was passed in. If the setting doesn't exist, the method returns null.

Removing a setting

The following example shows how to use the Settings.remove method to remove a setting with the name "themeColor". The only parameter of the remove method is the case-sensitive name of the setting.

Office.context.document.settings.remove('themeColor');

Nothing will happen if the setting does not exist. Use the Settings.saveAsync method to persist removal of the setting from the document.

Saving your settings

To save any additions, changes, or deletions your app made to the in-memory copy of the settings property bag during the current session, you must call the Settings.saveAsync method to store them in the document. The only parameter of the saveAsync method is callback, which is a callback function with a single parameter.

Office.context.document.settings.saveAsync(function (asyncResult) {
    if (asyncResult.status == Office.AsyncResultStatus.Failed) {
        write('Settings save failed. Error: ' + asyncResult.error.message);
    } else {
        write('Settings saved.');
    }
});
// Function that writes to a div with id='message' on the page.
function write(message){
    document.getElementById('message').innerText += message; 
}

The anonymous function passed into the saveAsync method as the callback parameter is executed when the operation is completed. The asyncResult parameter of the callback provides access to an AsyncResult object that contains the status of the operation. In the example, the function checks the AsyncResult.status property to see if the save operation succeeded or failed, and then displays the result in the app's page.

A mail app can use the RoamingSettings object to save app state and settings data that is specific to the user's mailbox. This data is accessible only by that mail app on behalf of the user running the app. The data is stored on the user's Exchange Server mailbox, and is accessible when that user logs into his or her account and runs the mail app in Outlook.

Loading roaming settings

A mail app typically loads roaming settings in the Office.initialize event handler. The following JavaScript code example shows how to load existing roaming settings.

var _mailbox;
var _settings;

// The initialize function is required for all apps.
Office.initialize = function (reason) {
    // Checks for the DOM to load using the jQuery ready function.
    $(document).ready(function () {
    // After the DOM is loaded, app-specific code can run.
   // Initialize instance variables to access API objects.
    _mailbox = Office.context.mailbox;
    _settings = Office.context.roamingSettings;
    });
}

Creating or assigning a roaming setting

Continuing with the preceding example, the following setAppSetting function shows how to use the RoamingSettings.set method to set or update a setting named cookie with today's date. Then, it saves all the roaming settings back to the Exchange Server with the RoamingSettings.saveAsync method.

// Set an app setting.
function setAppSetting() {
    _settings.set("cookie", Date());
    _settings.saveAsync(saveMyAppSettingsCallback);
}

// Saves all roaming settings.
function saveMyAppSettingsCallback(asyncResult) {
    if (asyncResult.status == Office.AsyncResultStatus.Failed) {
        // Handle the failure.
    }
}

The saveAsync method saves roaming settings asynchronously and takes an optional callback function. This code sample passes a callback function named saveMyAppSettingsCallback to the saveAsync method. When the asynchronous call returns, the asyncResult parameter of the saveMyAppSettingsCallback function provides access to an AsyncResult object that you can use to determine the success or failure of the operation with the AsyncResult.status property.

Removing a roaming setting

Also extending the preceding examples, the following removeAppSetting function, shows how to use the RoamingSettings.remove method to remove the cookie setting and save all the roaming settings back to the Exchange Server.

// Remove an application setting.
function removeAppSetting()
{
    _settings.remove("cookie");
    _settings.saveAsync(saveMyAppSettingsCallback);
}

Custom properties let your mail app store information about an item it is working with. For example, if your mail app creates an appointment from a meeting suggestion in a message, you can use custom properties to store the fact that the meeting was created. This makes sure that if the message is opened again, your mail app doesn't offer to create the appointment again.

Before you can use custom properties for a particular message, appointment, or meeting request item, you must load the properties into memory by calling the loadCustomPropertiesAsync method of the Item object. If any custom properties are already set for the current item, they are loaded from the Exchange server at this point. After you have loaded the properties, you can use the set and get methods of the CustomProperties object to add, update, and retrieve properties in memory. To save any changes that you make to the item's custom properties, you must use the saveAsync method to persist the changes to the item on the Exchange server.

Custom properties example

The following example shows a simplified set of functions for a mail app that uses custom properties. You can use this example as a starting point for your mail app that uses custom properties.

A mail app that uses these functions retrieves any custom properties by calling the get method on the _customProps variable, as shown in the following example.

var property = _customProps.get("propertyName");

This example includes the following functions:

Function name

Description

Office.initialize

Initializes the app and loads the custom properties for the current item from the Exchange server.

customPropsCallback

Gets the custom properties that are returned from the Exchange server and saves it for later use.

updateProperty

Sets or updates a specific property, and then saves the change to the Exchange server.

removeProperty

Removes a specific property, and then persists the removal to the Exchange server.

saveCallback

Callback for calls to the saveAsync method in the updateProperty and removeProperty functions.

var _mailbox;
var _customProps;

// The initialize function is required for all apps.
Office.initialize = function (reason) {
    // Checks for the DOM to load using the jQuery ready function.
    $(document).ready(function () {
    // After the DOM is loaded, app-specific code can run.
    _mailbox = Office.context.mailbox;
    _mailbox.item.loadCustomPropertiesAsync(customPropsCallback);
    });
}

// Get the item's custom properties from the server and save for later use.
function customPropsCallback(asyncResult) {
    _customProps = asyncResult.value;
}

// Sets or updates the specified property, and then saves the change 
// to the server.
function updateProperty(name, value) {
    _customProps.set(name, value);
    _customProps.saveAsync(saveCallback);
}

// Removes the specified property, and then persists the removal 
// to the server.
function removeProperty(name) {
   _customProps.remove(name);
   _customProps.saveAsync(saveCallback);
}

// Callback for calls to saveAsync method. 
function saveCallback(asyncResult) {
    if (asyncResult.status == Office.AsyncResultStatus.Failed) {
        // Handle the failure.
    }
}
Show:
© 2014 Microsoft