Export (0) Print
Expand All

Understanding the JavaScript API for Office

apps for Office

This topic provides a conceptual overview of the JavaScript API for Office, which is implemented in the Office.js file.

Last modified: July 21, 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 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

   Office.js: v1.0, v1.1

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

The JavaScript API for Office library is implemented in the Office.js file and associated .js files that contain application-specific implementations, such as Excel-15.js and Outlook-15.js. Reference the JavaScript API for Office library inside the <head> tag of the web page (such as an .html, .aspx, or .php file) that implements the UI of your app by using a script tag with its src attribute set to the following CDN URL:

<script src="https://appsforoffice.microsoft.com/lib/1.1/hosted/office.js"/>

This will download and cache the JavaScript API for Office files the first time your app loads to make sure that it is using the most up-to-date implementation of Office.js and its associated files for the specified version.

Applies to: All app types

The JavaScript API for Office provides the Office object, which lets the developer implement a listener for the initialize event of an app for Office. When the API is loaded and ready for the app to start interacting with user's content, it triggers the Office.initialize event. You can use code in the initialize event handler to implement common app initialization scenarios, such as prompting the user to select some cells in Excel, and then inserting a chart initialized with those selected values. You can also use the initialize event handler to initialize other custom logic for your app, such as establishing bindings, prompting for default app settings values, and so on.

Important: Even if your app has no initialization tasks to perform, you must include at least a minimal Office.initialize event handler function like the following example.

Office.initialize = function () {
};

If you fail to include an Office.initialize event handler, your app may raise an error when it starts. Also, if a user attempts to use your app with an Office Online web client, such as Excel Online, PowerPoint Online, or Outlook Web App, it will fail to run.

If your app includes more than one page, whenever it loads a new page that page must include or call an Office.initialize event handler.

For more detail about the sequence of events when an app is initialized, see Loading the DOM and runtime environment.

For task pane and content apps (but, not mail apps), the reason parameter of the initialize event listener function provides access to the InitializationReason enumeration that specifies how the initialization occurred. For example, a task pane or content app can be initialized because the user inserted it from the Office client's ribbon UI, or because a document that already contains the app was opened.

You can use the value of the InitializationReason enumeration to implement different logic for when the app is first inserted versus when it already exists in the document. The following example shows some simple logic you can add to the previous example to use the value of the reason argument to display how the task pane or content app was initialized.

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.
    // Display initialization reason.
    if (reason == "inserted")
    write("The app was just inserted.");

    if (reason == "documentOpened")
    write("The app is already part of the document.");
    });
}

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

Applies to: All app types

When an app is initialized, it has many different objects that it can interact with in the runtime environment. The app's runtime context is reflected in the API by the Context object. The Context is the main object that provides access to the most important objects of the API, such as the Document and Mailbox objects, which in turn provide access to document and mailbox content.

For example, in task pane or content apps, you can use the document property of the Context object to access the properties and methods of the Document object to interact with the content of Word documents, Excel worksheets, or Project schedules. Similarly, in mail apps, you can use the mailbox property of the Context object to access the properties and methods of the Mailbox object to interact with the message, meeting request, or appointment content.

The Context object also provides access to the contentLanguage and displayLanguage properties that let you determine the locale (language) used in the document or item, or by the host application. And, the roamingSettings property that lets you access the members of the RoamingSettings object.

Applies to: Content and task pane app types

To interact with document data in Excel, PowerPoint, and Word, the API provides the Document object. You can use Document object members to access data from the following ways:

  • Read and write to active selections in the form of text, contiguous cells (matrices), or tables.

  • Tabular data (matrices or tables).

  • Bindings (created with the "add" methods of the Bindings object).

  • Custom XML parts (only for Word).

  • Settings or app state persisted per app on the document.

You can also use the Document object to interact with data in Project documents. The Project-specific functionality of the API is documented in the members ProjectDocument abstract class. For more information about creating task pane apps for Project, see Task pane apps for Project.

All these forms of data access start from an instance of the abstract Document object.

You can access an instance of the Document object when the task pane or content app is initialized by using the document property of the Context object. The Document object defines common data access functions shared across Word and Excel documents, and also provides access to the CustomXmlParts object for Word documents.

The Document object supports four ways for developers to access document contents:

  • Selection-based access

  • Binding-based access

  • Custom XML part-based access (Word only)

  • Entire document-based access (PowerPoint and Word only)

To help you understand how selection- and binding-based data access methods work, we will first explain how the data-access APIs provide consistent data access across different Office applications.

Consistent data access across Office applications

Applies to: Content and task pane app types

To create extensions that seamlessly work across different Office documents, the JavaScript API for Office abstracts away the particularities of each Office application through common data types and the ability to coerce different document contents into three common data types.

Common data types

In both selection-based and binding-based data access, document contents are exposed through data types that are common across all the supported Office applications. In Office 2013, three main data types are supported:

Data type

Description

Host application support

Text

Provides a string representation of the data in the selection or binding.

In Excel 2013, Project 2013, and PowerPoint 2013 only plain text is supported. In Word 2013, three text formats are supported: plain text, HTML, and Office Open XML (OOXML).

When text is selected in a cell in Excel, selection-based methods read and write to the entire contents of the cell, even if only a portion of the text is selected in the cell. When text is selected in Word and PowerPoint, selection-based methods read and write only to the run of characters that are selected.

Project 2013 and PowerPoint 2013 support only selection-based data access.

Matrix

Provides the data in the selection or binding as a two dimensional Array, which in JavaScript is implemented as an array of arrays.

For example, two rows of string values in two columns would be [['a', 'b'], ['c', 'd']], and a single column of three rows would be [['a'], ['b'], ['c']].

Matrix data access is supported only in Excel 2013 and Word 2013.

Table

Provides the data in the selection or binding as a TableData object. The TableData object exposes the data through the headers and rows properties.

Table data access is supported only in Excel 2013 and Word 2013.

Data type coercion

The data access methods on the Document and Binding objects support specifying the desired data type using the coercionType parameter of these methods, and corresponding CoercionType enumeration values. Regardless of the actual shape of the binding, the different Office applications support the common data types by trying to coerce the data into the requested data type. For example, if a Word table or paragraph is selected, the developer can specify to read it as plain text, HTML, Office Open XML, or a table, and the API implementation handles the necessary transformations and data conversions.

Tip Tip

When should you use the matrix versus table coercionType for data access? If you need your tabular data to grow dynamically when rows and columns are added, and you must work with table headers, you should use the table data type (by specifying the coercionType parameter of a Document or Binding object data access method as "table" or Office.CoercionType.Table). Adding rows and columns within the data structure is supported in both table and matrix data, but appending rows and columns is supported only for table data.

If you are you aren't planning on adding rows and columns, and your data doesn't require header functionality, then you should use the matrix data type (by specifying the coercionType parameter of the data access method as "matrix" or Office.CoercionType.Matrix), which provides a simpler model of interacting with the data.

If the data can't be coerced to the specified type, the AsyncResult.status property in the callback returns "failed", and you can use the AsyncResult.error property to access an Error object with information about why the method call failed.

The Document object exposes methods that let you to read and write to the user's current selection in a "get and forget" fashion. To do that, the Document object provides the getSelectedDataAsync and setSelectedDataAsync methods.

For code examples that demonstrate how to perform tasks with selections, see Reading and writing data to the active selection in a document or spreadsheet.

Binding-based data access enables content and task pane apps to consistently access a particular region of a document or spreadsheet through an identifier associated with a binding. The app first needs to establish the binding by calling one of the methods that associates a portion of the document with a unique identifier: addFromPromptAsync, addFromSelectionAsync, or addFromNamedItemAsync. After the binding is established, the app can use the provided identifier to access the data contained in the associated region of the document or spreadsheet. Creating bindings provides the following value to your app:

  • Permits access to common data structures across supported Office applications, such as: tables, ranges, or text (a contiguous run of characters).

  • Enables read/write operations without requiring the user to make a selection.

  • Establishes a relationship between the app and the data in the document. Bindings are persisted in the document, and can be accessed at a later time.

Establishing a binding also allows you to subscribe to data and selection change events that are scoped to that particular region of the document or spreadsheet. This means that the app is only notified of changes that happen within the bound region as opposed to general changes across the whole document or spreadsheet.

The Bindings object exposes a getAllAsync method that gives access to the set of all bindings established on the document or spreadsheet. An individual binding can be accessed by its ID using either the Bindings.getBindingByIdAsync or Office.select methods. You can establish new bindings as well as remove existing ones by using one of the following methods of the Bindings object: addFromSelectionAsync, addFromPromptAsync, addFromNamedItemAsync, or releaseByIdAsync.

There are three different types of bindings that you specify with the bindingType parameter when you create a binding with the addFromSelectionAsync, addFromPromptAsync or addFromNamedItemAsync methods:

Binding type

Description

Host application support

Text binding

Binds to a region of the document that can be represented as text.

In Word, most contiguous selections are valid, while in Excel only single cell selections can be the target of a text binding. In Excel, only plain text is supported. In Word, three formats are supported: plain text, HTML, and Open XML for Office.

Matrix binding

Binds to a fixed region of a document that contains tabular data without headers.

Data in a matrix binding is written or read as a two dimensional Array, which in JavaScript is implemented as an array of arrays. For example, two rows of string values in two columns can be written or read as [['a', 'b'], ['c', 'd']], and a single column of three rows can be written or read as [['a'], ['b'], ['c']].

In Excel, any contiguous selection of cells can be used to establish a matrix binding. In Word, only tables support matrix binding.

Table binding

Binds to a region of a document that contains a table with headers.

Data in a table binding is written or read as a TableData object. The TableData object exposes the data through the headers and rows properties.

Any Excel or Word table can be the basis for a table binding. After you establish a table binding, each new row or column a user adds to the table is automatically included in the binding.

After a binding is created by using one of the three "add" methods of the Bindings object, you can work with the binding's data and properties by using the methods of the corresponding object: MatrixBinding, TableBinding, or TextBinding. All three of these objects inherit the getDataAsync and setDataAsync methods of the Binding object that enable to you interact with the bound data.

For code examples that demonstrate how to perform tasks with bindings, see Binding to regions in a document or spreadsheet.

Applies to: Task pane apps for Word

The CustomXmlParts and CustomXmlPart objects of the API provide access to custom XML parts in Word documents, which enable XML-driven manipulation of the contents of the document. For demonstrations of working with the CustomXmlParts and CustomXmlPart objects, see the Work with custom XML parts code sample.

Applies to: Task pane apps for Word and PowerPoint

The Document.getFileAsync method and members of the File and Slice objects to provide functionality for getting entire Word and PowerPoint document files in slices (chunks) of up to 4 MB at a time. For more information, see How to: Get all file content from a document in an app.

Applies to: Mail apps

Mail apps primarily use a subset of the API exposed through the Mailbox object. To access the objects and members specifically for use in mail apps, such as the Item object, you use the mailbox property of the Context object to access the Mailbox object, as shown in the following line of code.

// Access the Item object.
var item = Office.context.mailbox.item;

Additionally, mail apps can use the following objects:

  • Office object—for initialization.

  • Context object—for access to content and display language properties.

  • RoamingSettings object—for saving mail-app-specific custom settings to the user's mailbox where the app is installed.

For information about using JavaScript in mail apps, see Mail apps for Outlook and Start with fundamental concepts for mail apps in Outlook.

This table summarizes the API and features supported across app types (content, task pane, and mail) and the Office applications that can host them when you specify the Office host applications your app supports using the 1.1 app manifest schema and features supported by v1.1 JavaScript API for Office.

Host name

Database

Workbook

Mailbox

Presentation

Document

Project

Supported
Host applications

Access app for SharePoint

Excel
Excel RT
Excel Online

Outlook
Outlook RT
Outlook Web App
OWA for Devices

PowerPoint
PowerPoint RT
PowerPoint Online

Word
Word RT

Project

Supported app types

Content

Task pane

Mail

Supported API features

Read/Write Text


Read only

Read/Write Matrix

Read/Write Table

Read/Write HTML

Read/Write
Office Open XML

Read task, resource,
view, and field properties

Selection changed events

Get whole document

Bindings
and binding events


Only full and partial
table bindings

Read/Write
Custom Xml Parts

Persist app state data
(settings)


Per host app


Per document


Per mailbox


Per document


Per document

Settings changed events

Get active view mode
and view changed events

Navigate to locations
in the document

Activate contextually
using rules and RegEx

Read Item properties

Read User profile

Get attachments

Get User identity token

Call Exchange Web Services

Show:
© 2014 Microsoft