Office.Document interface

An abstract class that represents the document the add-in is interacting with.

Remarks

Applications: Excel, PowerPoint, Project, Word

Examples

// Get the Document object with the Common APIs.
const document : Office.Document = Office.context.document;

Properties

bindings

Gets an object that provides access to the bindings defined in the document.

customXmlParts

Gets an object that represents the custom XML parts in the document.

mode

Gets the mode the document is in.

settings

Gets an object that represents the saved custom settings of the content or task pane add-in for the current document.

url

Gets the URL of the document that the Office application currently has open. Returns null if the URL is unavailable.

Methods

addHandlerAsync(eventType, handler, options, callback)

Adds an event handler for a Document object event.

addHandlerAsync(eventType, handler, callback)

Adds an event handler for a Document object event.

getActiveViewAsync(options, callback)

Returns the state of the current view of the presentation (edit or read).

getActiveViewAsync(callback)

Returns the state of the current view of the presentation (edit or read).

getFileAsync(fileType, options, callback)

Returns the entire document file in slices of up to 4194304 bytes (4 MB). For add-ins on iPad, file slice is supported up to 65536 (64 KB). Note that specifying file slice size of above permitted limit will result in an "Internal Error" failure.

getFileAsync(fileType, callback)

Returns the entire document file in slices of up to 4194304 bytes (4 MB). For add-ins on iPad, file slice is supported up to 65536 (64 KB). Note that specifying file slice size of above permitted limit will result in an "Internal Error" failure.

getFilePropertiesAsync(options, callback)

Gets file properties of the current document.

getFilePropertiesAsync(callback)

Gets file properties of the current document.

getMaxResourceIndexAsync(options, callback)

Project documents only. Get the maximum index of the collection of resources in the current project.

Important: This API works only in Project on Windows desktop.

getMaxResourceIndexAsync(callback)

Project documents only. Get the maximum index of the collection of resources in the current project.

Important: This API works only in Project on Windows desktop.

getMaxTaskIndexAsync(options, callback)

Project documents only. Get the maximum index of the collection of tasks in the current project.

Important: This API works only in Project on Windows desktop.

getMaxTaskIndexAsync(callback)

Project documents only. Get the maximum index of the collection of tasks in the current project.

Important: This API works only in Project on Windows desktop.

getProjectFieldAsync(fieldId, options, callback)

Project documents only. Get Project field (e.g., ProjectWebAccessURL).

getProjectFieldAsync(fieldId, callback)

Project documents only. Get Project field (e.g., ProjectWebAccessURL).

getResourceByIndexAsync(resourceIndex, options, callback)

Project documents only. Get the GUID of the resource that has the specified index in the resource collection.

Important: This API works only in Project on Windows desktop.

getResourceByIndexAsync(resourceIndex, callback)

Project documents only. Get the GUID of the resource that has the specified index in the resource collection.

Important: This API works only in Project on Windows desktop.

getResourceFieldAsync(resourceId, fieldId, options, callback)

Project documents only. Get resource field for provided resource ID. (e.g., ResourceName)

getResourceFieldAsync(resourceId, fieldId, callback)

Project documents only. Get resource field for provided resource ID. (e.g., ResourceName)

getSelectedDataAsync(coercionType, options, callback)

Reads the data contained in the current selection in the document.

getSelectedDataAsync(coercionType, callback)

Reads the data contained in the current selection in the document.

getSelectedResourceAsync(options, callback)

Project documents only. Get the current selected Resource's ID.

getSelectedResourceAsync(callback)

Project documents only. Get the current selected Resource's ID.

getSelectedTaskAsync(options, callback)

Project documents only. Get the current selected Task's ID.

getSelectedTaskAsync(callback)

Project documents only. Get the current selected Task's Id.

getSelectedViewAsync(options, callback)

Project documents only. Get the current selected View Type (e.g., Gantt) and View Name.

getSelectedViewAsync(callback)

Project documents only. Get the current selected View Type (e.g., Gantt) and View Name.

getTaskAsync(taskId, options, callback)

Project documents only. Get the Task Name, WSS Task ID, and ResourceNames for given taskId.

getTaskAsync(taskId, callback)

Project documents only. Get the Task Name, WSS Task ID, and ResourceNames for given taskId.

getTaskByIndexAsync(taskIndex, options, callback)

Project documents only. Get the GUID of the task that has the specified index in the task collection.

Important: This API works only in Project on Windows desktop.

getTaskByIndexAsync(taskIndex, callback)

Project documents only. Get the GUID of the task that has the specified index in the task collection.

Important: This API works only in Project on Windows desktop.

getTaskFieldAsync(taskId, fieldId, options, callback)

Project documents only. Get task field for provided task ID. (e.g., StartDate).

getTaskFieldAsync(taskId, fieldId, callback)

Project documents only. Get task field for provided task ID. (e.g., StartDate).

getWSSUrlAsync(options, callback)

Project documents only. Get the WSS Url and list name for the Tasks List, the MPP is synced too.

getWSSUrlAsync(callback)

Project documents only. Get the WSS URL and list name for the Tasks List, the MPP is synced too.

goToByIdAsync(id, goToType, options, callback)

Goes to the specified object or location in the document.

goToByIdAsync(id, goToType, callback)

Goes to the specified object or location in the document.

removeHandlerAsync(eventType, options, callback)

Removes an event handler for the specified event type.

removeHandlerAsync(eventType, callback)

Removes an event handler for the specified event type.

setResourceFieldAsync(resourceId, fieldId, fieldValue, options, callback)

Project documents only. Set resource field for specified resource ID.

Important: This API works only in Project on Windows desktop.

setResourceFieldAsync(resourceId, fieldId, fieldValue, callback)

Project documents only. Set resource field for specified resource ID.

Important: This API works only in Project on Windows desktop.

setSelectedDataAsync(data, options, callback)

Writes the specified data into the current selection.

setSelectedDataAsync(data, callback)

Writes the specified data into the current selection.

setTaskFieldAsync(taskId, fieldId, fieldValue, options, callback)

Project documents only. Set task field for specified task ID.

Important: This API works only in Project on Windows desktop.

setTaskFieldAsync(taskId, fieldId, fieldValue, callback)

Project documents only. Set task field for specified task ID.

Important: This API works only in Project on Windows desktop.

Property Details

bindings

Gets an object that provides access to the bindings defined in the document.

bindings: Bindings;

Property Value

Remarks

You don't instantiate the Document object directly in your script. To call members of the Document object to interact with the current document or worksheet, use Office.context.document in your script.

Examples

function displayAllBindings() {
    Office.context.document.bindings.getAllAsync(function (asyncResult) {
        let bindingString = '';
        for (let i in asyncResult.value) {
            bindingString += asyncResult.value[i].id + '\n';
        }
        write('Existing bindings: ' + bindingString);
    });
}

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

customXmlParts

Gets an object that represents the custom XML parts in the document.

customXmlParts: CustomXmlParts;

Property Value

Examples

function getCustomXmlParts(){
    Office.context.document.customXmlParts.getByNamespaceAsync('http://tempuri.org', function (asyncResult) {
        write('Retrieved ' + asyncResult.value.length + ' custom XML parts');
    });
}

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

mode

Gets the mode the document is in.

mode: DocumentMode;

Property Value

Examples

function displayDocumentMode() {
    write(Office.context.document.mode);
}

// Function that writes to a div with id='message' on the page.
function write(message){
    document.getElementById('message').innerText += message; 
}
// The following example initializes the add-in and then gets properties of the
// Document object that are available in the context of a Project document.
// A Project document is the opened, active project. To access members of the
// ProjectDocument object, use the Office.context.document object as shown in
// the code examples for ProjectDocument methods and events.
// The example assumes your add-in has a reference to the jQuery library and
// that the following page control is defined in the content div in the page body:
// <span id="message"></span>

(function () {
    "use strict";

    // The initialize function must be run each time a new page is loaded.
    Office.initialize = function (reason) {
        $(document).ready(function () {

            // Get information about the document.
            showDocumentProperties();
        });
    };

    // Get the document mode and the URL of the active project.
    function showDocumentProperties() {
        const output = String.format(
            'The document mode is {0}.<br/>The URL of the active project is {1}.',
            Office.context.document.mode,
            Office.context.document.url);
        $('#message').html(output);
    }
})();

settings

Gets an object that represents the saved custom settings of the content or task pane add-in for the current document.

settings: Settings;

Property Value

url

Gets the URL of the document that the Office application currently has open. Returns null if the URL is unavailable.

url: string;

Property Value

string

Examples

function displayDocumentUrl() {
    write(Office.context.document.url);
}

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

Method Details

addHandlerAsync(eventType, handler, options, callback)

Adds an event handler for a Document object event.

addHandlerAsync(eventType: Office.EventType, handler: any, options?: Office.AsyncContextOptions, callback?: (result: AsyncResult<void>) => void): void;

Parameters

eventType
Office.EventType

For a Document object event, the eventType parameter can be specified as Office.EventType.Document.SelectionChanged or Office.EventType.Document.ActiveViewChanged, or the corresponding text value of this enumeration.

handler

any

The event handler function to add, whose only parameter is of type Office.DocumentSelectionChangedEventArgs. Required.

options
Office.AsyncContextOptions

Provides an option for preserving context data of any type, unchanged, for use in a callback.

callback

(result: Office.AsyncResult<void>) => void

Optional. A function that is invoked when the callback returns, whose only parameter is of type Office.AsyncResult.

Returns

void

Remarks

Requirement set: DocumentEvents

You can add multiple event handlers for the specified eventType as long as the name of each event handler function is unique.

addHandlerAsync(eventType, handler, callback)

Adds an event handler for a Document object event.

addHandlerAsync(eventType: Office.EventType, handler: any, callback?: (result: AsyncResult<void>) => void): void;

Parameters

eventType
Office.EventType

For a Document object event, the eventType parameter can be specified as Office.EventType.Document.SelectionChanged or Office.EventType.Document.ActiveViewChanged, or the corresponding text value of this enumeration.

handler

any

The event handler function to add, whose only parameter is of type Office.DocumentSelectionChangedEventArgs. Required.

callback

(result: Office.AsyncResult<void>) => void

Optional. A function that is invoked when the callback returns, whose only parameter is of type Office.AsyncResult.

Returns

void

Remarks

Requirement set: DocumentEvents

You can add multiple event handlers for the specified eventType as long as the name of each event handler function is unique.

Examples

// The following example adds an event handler for the SelectionChanged event of a document
function addSelectionChangedEventHandler() {
    Office.context.document.addHandlerAsync(Office.EventType.DocumentSelectionChanged, MyHandler);
}

function MyHandler(eventArgs) {
    write('Event raised: ' + eventArgs.type);
    doSomethingWithDocument(eventArgs.document);
}

// Function that writes to a div with id='message' on the page.
function write(message){
    document.getElementById('message').innerText += message; 
}
// The following code example adds a handler for the ResourceSelectionChanged event.
// When the resource selection changes in the document, it gets the GUID of the selected resource.
// The example assumes your add-in has a reference to the jQuery library and that the
// following page control is defined in the content div in the page body:
// <span id="message"></span>

(function () {
    "use strict";

    // The initialize function must be run each time a new page is loaded.
    Office.initialize = function (reason) {
        $(document).ready(function () {

            // After the DOM is loaded, add-in-specific code can run.
            Office.context.document.addHandlerAsync(
                Office.EventType.ResourceSelectionChanged,
                getResourceGuid);
        });
    };

    // Get the GUID of the selected resource and display it in the add-in.
    function getResourceGuid() {
        Office.context.document.getSelectedResourceAsync(
            function (result) {
                if (result.status === Office.AsyncResultStatus.Failed) {
                    onError(result.error);
                }
                else {
                    $('#message').html(result.value);
                }
            }
        );
    }

    function onError(error) {
        $('#message').html(error.name + ' ' + error.code + ': ' + error.message);
    }
})();

// For a complete code sample that shows how to use a ResourceSelectionChanged
// event handler in a Project add-in, see "Create your first task pane add-in for Microsoft Project".
// https://learn.microsoft.com/office/dev/add-ins/project/create-your-first-task-pane-add-in-for-project-by-using-a-text-editor
// The following code example adds a handler for the TaskSelectionChanged event.
// When the task selection changes in the document, it gets the GUID of the
// selected task.
// The example assumes your add-in has a reference to the jQuery library and that
// the following page control is defined in the content div in the page body:
// <span id="message"></span>

(function () {
    "use strict";

    // The initialize function must be run each time a new page is loaded.
    Office.initialize = function (reason) {
        $(document).ready(function () {

            // After the DOM is loaded, add-in-specific code can run.
            Office.context.document.addHandlerAsync(
                Office.EventType.TaskSelectionChanged,
                getTaskGuid);
            getTaskGuid();
        });
    };

    // Get the GUID of the selected task and display it in the add-in.
    function getTaskGuid() {
        Office.context.document.getSelectedTaskAsync(
            function (result) {
                if (result.status === Office.AsyncResultStatus.Failed) {
                    onError(result.error);
                }
                else {
                    $('#message').html(result.value);
                }
            }
        );
    }

    function onError(error) {
        $('#message').html(error.name + ' ' + error.code + ': ' + error.message);
    }
})();
// The following code example adds a handler for the ViewSelectionChanged
// event. When the active view changes, it gets the name and type of the active view.
// The example assumes your add-in has a reference to the jQuery library and that
// the following page control is defined in the content div in the page body:
// <span id="message"></span>

(function () {
    "use strict";

    // The initialize function must be run each time a new page is loaded.
    Office.initialize = function (reason) {
        $(document).ready(function () {

            // After the DOM is loaded, add-in-specific code can run.
            Office.context.document.addHandlerAsync(
                Office.EventType.ViewSelectionChanged,
                getActiveView);
            getActiveView();
        });
    };

    // Get the name and type of the active view and display it in the add-in.
    function getActiveView() {
        Office.context.document.getSelectedViewAsync(
            function (result) {
                if (result.status === Office.AsyncResultStatus.Failed) {
                    onError(result.error);
                }
                else {
                    const output = String.format(
                        'View name: {0}<br/>View type: {1}',
                        result.value.viewName, result.value.viewType);
                    $('#message').html(output);
                }
            }
        );
    }

    function onError(error) {
        $('#message').html(error.name + ' ' + error.code + ': ' + error.message);
    }
})();

// For an example that shows how to use a ViewSelectionChanged event handler in a
// Project add-in, see "Create your first task pane add-in for Microsoft Project".
// https://learn.microsoft.com/office/dev/add-ins/project/create-your-first-task-pane-add-in-for-project-by-using-a-text-editor
// The following code example uses addHandlerAsync to add an event handler for the ViewSelectionChanged event.
// When the active view changes, the handler checks the view type. It enables a button if the view is a resource
// view and disables the button if it isn't a resource view. Choosing the button gets the GUID of the selected
// resource and displays it in the add-in.
// The example assumes that your add-in has a reference to the jQuery library and that the following page controls
// are defined in the content div in the page body:
// <input id="get-info" type="button" value="Get info" disabled="disabled" /><br />
// <span id="message"></span>

(function () {
    "use strict";

    // The initialize function must be run each time a new page is loaded.
    Office.initialize = function (reason) {
        $(document).ready(function () {

            // After the DOM is loaded, add-in-specific code can run.
            // Add a ViewSelectionChanged event handler.
            Office.context.document.addHandlerAsync(
                Office.EventType.ViewSelectionChanged,
                getActiveView);
            $('#get-info').on("click", getResourceGuid);

            // This example calls the handler on page load to get the active view
            // of the default page.
            getActiveView();
        });
    };

    // Activate the button based on the active view type of the document.
    // This is the ViewSelectionChanged event handler.
    function getActiveView() {
        Office.context.document.getSelectedViewAsync(
            function (result) {
                if (result.status === Office.AsyncResultStatus.Failed) {
                    onError(result.error);
                }
                else {
                    const viewType = result.value.viewType;
                    if (viewType == 6 ||   // ResourceForm
                        viewType == 7 ||   // ResourceSheet
                        viewType == 8 ||   // ResourceGraph
                        viewType == 15) {  // ResourceUsage
                        $('#get-info').removeAttr('disabled');
                    }
                    else {
                        $('#get-info').attr('disabled', 'disabled');
                    }
                    const output = String.format(
                        'View name: {0}<br/>View type: {1}',
                        result.value.viewName, viewType);
                    $('#message').html(output);
                }
            }
        );
    }

    // Get the GUID of the currently selected resource and display it in the add-in.
    function getResourceGuid() {
        Office.context.document.getSelectedResourceAsync(
            function (result) {
                if (result.status === Office.AsyncResultStatus.Failed) {
                    onError(result.error);
                }
                else {
                    $('#message').html('Resource GUID: ' + result.value);
                }
            }
        );
    }

    function onError(error) {
        $('#message').html(error.name + ' ' + error.code + ': ' + error.message);
    }
})();

// For a complete code sample that shows how to use a ViewSelectionChanged event handler in a Project add-in,
// see "Create your first task pane add-in for Project by using a text editor."
// https://learn.microsoft.com/office/dev/add-ins/project/create-your-first-task-pane-add-in-for-project-by-using-a-text-editor

getActiveViewAsync(options, callback)

Returns the state of the current view of the presentation (edit or read).

getActiveViewAsync(options?: Office.AsyncContextOptions, callback?: (result: AsyncResult<"edit" | "read">) => void): void;

Parameters

options
Office.AsyncContextOptions

Provides an option for preserving context data of any type, unchanged, for use in a callback.

callback

(result: Office.AsyncResult<"edit" | "read">) => void

Optional. A function that is invoked when the callback returns, whose only parameter is of type Office.AsyncResult. The value property of the result is the state of the presentation's current view. The value returned can be either "edit" or "read". "edit" corresponds to any of the views in which you can edit slides: Normal, Slide Sorter, or Outline View. "read" corresponds to either Slide Show or Reading View.

Returns

void

Remarks

Requirement set: ActiveView

Can trigger an event when the view changes.

getActiveViewAsync(callback)

Returns the state of the current view of the presentation (edit or read).

getActiveViewAsync(callback?: (result: AsyncResult<"edit" | "read">) => void): void;

Parameters

callback

(result: Office.AsyncResult<"edit" | "read">) => void

Optional. A function that is invoked when the callback returns, whose only parameter is of type Office.AsyncResult. The value property of the result is the state of the presentation's current view. The value returned can be either "edit" or "read". "edit" corresponds to any of the views in which you can edit slides: Normal, Slide Sorter, or Outline View. "read" corresponds to either Slide Show or Reading View.

Returns

void

Remarks

Requirement set: ActiveView

Can trigger an event when the view changes.

Examples

function getFileView() {
    // Get whether the current view is edit or read.
    Office.context.document.getActiveViewAsync(function (asyncResult) {
        if (asyncResult.status == "failed") {
            showMessage("Action failed with error: " + asyncResult.error.message);
        }
        else {
            showMessage(asyncResult.value);
        }
    });
}

getFileAsync(fileType, options, callback)

Returns the entire document file in slices of up to 4194304 bytes (4 MB). For add-ins on iPad, file slice is supported up to 65536 (64 KB). Note that specifying file slice size of above permitted limit will result in an "Internal Error" failure.

getFileAsync(fileType: FileType, options?: GetFileOptions, callback?: (result: AsyncResult<Office.File>) => void): void;

Parameters

fileType
Office.FileType

The format in which the file will be returned

options
Office.GetFileOptions

Provides options for setting the size of slices that the document will be divided into.

callback

(result: Office.AsyncResult<Office.File>) => void

Optional. A function that is invoked when the callback returns, whose only parameter is of type Office.AsyncResult. The value property of the result is the File object.

Returns

void

Remarks

Requirement sets:

For add-ins running in Office applications other than Office on iPad, the getFileAsync method supports getting files in slices of up to 4194304 bytes (4 MB). For add-ins running in Office apps on iPad, the getFileAsync method supports getting files in slices of up to 65536 (64 KB).

The fileType parameter can be specified by using the Office.FileType enumeration or text values. But the possible values vary with the application.

Supported FileTypes, by platform

Office on the web Office on Windows Office on Mac Office on iPad
Excel Compressed, Pdf Compressed, Pdf, TextCompressed, Pdf, Text Not supported
PowerPoint Compressed, Pdf Compressed, Pdf Compressed, Pdf Compressed, Pdf
Word Compressed, Pdf, TextCompressed, Pdf, TextCompressed, Pdf, TextCompressed, Pdf

Examples

// The following example gets the document in Office Open XML ("compressed") format in 65536 bytes (64 KB) slices.
// Note: The implementation of app.showNotification in this example is from the Visual Studio template for Office Add-ins.
function getDocumentAsCompressed() {
    Office.context.document.getFileAsync(Office.FileType.Compressed, { sliceSize: 65536 /*64 KB*/ }, 
        function (result) {
            if (result.status == "succeeded") {
                // If the getFileAsync call succeeded, then
                // result.value will return a valid File Object.
                const myFile = result.value;
                const sliceCount = myFile.sliceCount;
                const docDataSlices = [];
                let slicesReceived = 0, gotAllSlices = true;
                app.showNotification("File size:" + myFile.size + " #Slices: " + sliceCount);

                // Get the file slices.
                getSliceAsync(myFile, 0, sliceCount, gotAllSlices, docDataSlices, slicesReceived);
            } else {
                app.showNotification("Error:", result.error.message);
            }
    });
}

function getSliceAsync(file, nextSlice, sliceCount, gotAllSlices, docDataSlices, slicesReceived) {
    file.getSliceAsync(nextSlice, function (sliceResult) {
        if (sliceResult.status == "succeeded") {
            if (!gotAllSlices) { /* Failed to get all slices, no need to continue. */
                return;
            }

            // Got one slice, store it in a temporary array.
            // (Or you can do something else, such as
            // send it to a third-party server.)
            docDataSlices[sliceResult.value.index] = sliceResult.value.data;
            if (++slicesReceived == sliceCount) {
              // All slices have been received.
              file.closeAsync();
              onGotAllSlices(docDataSlices);
            }
            else {
                getSliceAsync(file, ++nextSlice, sliceCount, gotAllSlices, docDataSlices, slicesReceived);
            }
        }
            else {
                gotAllSlices = false;
                file.closeAsync();
                app.showNotification("getSliceAsync Error:", sliceResult.error.message);
            }
    });
}

function onGotAllSlices(docDataSlices) {
    let docData = [];
    for (let i = 0; i < docDataSlices.length; i++) {
        docData = docData.concat(docDataSlices[i]);
    }

    let fileContent = new String();
    for (let j = 0; j < docData.length; j++) {
        fileContent += String.fromCharCode(docData[j]);
    }

    // Now all the file content is stored in 'fileContent' variable,
    // you can do something with it, such as print, fax...
}

// The following example gets the document in PDF format.
Office.context.document.getFileAsync(Office.FileType.Pdf,
    function(result) {
        if (result.status == "succeeded") {
            const myFile = result.value;
            const sliceCount = myFile.sliceCount;
            app.showNotification("File size:" + myFile.size + " #Slices: " + sliceCount);

            // Get the file slices.
            const docDataSlices = [];
            let slicesReceived = 0, gotAllSlices = true;
            getSliceAsync(myFile, 0, sliceCount, gotAllSlices, docDataSlices, slicesReceived);
            
            myFile.closeAsync();
        }
        else {
            app.showNotification("Error:", result.error.message);
        }
    }
);

getFileAsync(fileType, callback)

Returns the entire document file in slices of up to 4194304 bytes (4 MB). For add-ins on iPad, file slice is supported up to 65536 (64 KB). Note that specifying file slice size of above permitted limit will result in an "Internal Error" failure.

getFileAsync(fileType: FileType, callback?: (result: AsyncResult<Office.File>) => void): void;

Parameters

fileType
Office.FileType

The format in which the file will be returned

callback

(result: Office.AsyncResult<Office.File>) => void

Optional. A function that is invoked when the callback returns, whose only parameter is of type Office.AsyncResult. The value property of the result is the File object.

Returns

void

Remarks

Requirement sets:

For add-ins running in Office applications other than Office on iPad, the getFileAsync method supports getting files in slices of up to 4194304 bytes (4 MB). For add-ins running in Office apps on iPad, the getFileAsync method supports getting files in slices of up to 65536 (64 KB).

The fileType parameter can be specified by using the Office.FileType enumeration or text values. But the possible values vary with the application.

Supported FileTypes, by platform

Office on the web Office on Windows Office on Mac Office on iPad
Excel Compressed, Pdf Compressed, Pdf, TextCompressed, Pdf, Text Not supported
PowerPoint Compressed, Pdf Compressed, Pdf Compressed, Pdf Compressed, Pdf
Word Compressed, Pdf, TextCompressed, Pdf, TextCompressed, Pdf, TextCompressed, Pdf

getFilePropertiesAsync(options, callback)

Gets file properties of the current document.

getFilePropertiesAsync(options?: Office.AsyncContextOptions, callback?: (result: AsyncResult<Office.FileProperties>) => void): void;

Parameters

options
Office.AsyncContextOptions

Provides an option for preserving context data of any type, unchanged, for use in a callback.

callback

(result: Office.AsyncResult<Office.FileProperties>) => void

A function that is invoked when the callback returns, whose only parameter is of type Office.AsyncResult. The value property of the result is the file's properties (with the URL found at asyncResult.value.url).

Returns

void

Remarks

Requirement sets: Not in a set

You get the file's URL with the url property asyncResult.value.url.

getFilePropertiesAsync(callback)

Gets file properties of the current document.

getFilePropertiesAsync(callback?: (result: AsyncResult<Office.FileProperties>) => void): void;

Parameters

callback

(result: Office.AsyncResult<Office.FileProperties>) => void

A function that is invoked when the callback returns, whose only parameter is of type Office.AsyncResult. The value property of the result is the file's properties (with the URL found at asyncResult.value.url).

Returns

void

Remarks

Requirement sets: Not in a set

You get the file's URL with the url property asyncResult.value.url.

Examples

// To read the URL of the current file, you need to write a callback function that returns the URL.
// The following example shows how to:
// 1. Pass an anonymous callback function that returns the value of the file's URL
//    to the callback parameter of the getFilePropertiesAsync method.
// 2. Display the value on the add-in's page.
function getFileUrl() {
    // Get the URL of the current file.
    Office.context.document.getFilePropertiesAsync(function (asyncResult) {
        const fileUrl = asyncResult.value.url;
        if (fileUrl == "") {
            showMessage("The file hasn't been saved yet. Save the file and try again");
        }
        else {
            showMessage(fileUrl);
        }
    });
}

getMaxResourceIndexAsync(options, callback)

Project documents only. Get the maximum index of the collection of resources in the current project.

Important: This API works only in Project on Windows desktop.

getMaxResourceIndexAsync(options?: Office.AsyncContextOptions, callback?: (result: AsyncResult<number>) => void): void;

Parameters

options
Office.AsyncContextOptions

Provides an option for preserving context data of any type, unchanged, for use in a callback.

callback

(result: Office.AsyncResult<number>) => void

Optional. A function that is invoked when the callback returns, whose only parameter is of type Office.AsyncResult. The value property of the result is the highest index number in the current project's resource collection.

Returns

void

getMaxResourceIndexAsync(callback)

Project documents only. Get the maximum index of the collection of resources in the current project.

Important: This API works only in Project on Windows desktop.

getMaxResourceIndexAsync(callback?: (result: AsyncResult<number>) => void): void;

Parameters

callback

(result: Office.AsyncResult<number>) => void

Optional. A function that is invoked when the callback returns, whose only parameter is of type Office.AsyncResult. The value property of the result is the highest index number in the current project's resource collection.

Returns

void

Examples

// The following code example calls getResourceTaskIndexAsync to get the maximum index of the collection 
// of resources in the current project. Then it uses the returned value and the getResourceByIndexAsync
// method to get each resource GUID. The example assumes that your add-in has a reference to the 
// jQuery library and that the following page controls are defined in the content div in the page body:
// <input id="get-info" type="button" value="Get info" /><br />
// <span id="message"></span>

(function () {
    "use strict";
    const resourceGuids = [];

    // The initialize function must be run each time a new page is loaded.
    Office.initialize = function (reason) {
        $(document).ready(function () {

            // After the DOM is loaded, add-in-specific code can run.
            app.initialize();
            $('#get-info').on("click", getResourceInfo);
        });
    };

    // Get the maximum resource index, and then get the resource GUIDs.
    function getResourceInfo() {
        getMaxResourceIndex().then(
            function (data) {
                getResourceGuids(data);
            }
        );
    }

    // Get the maximum index of the resources for the current project.
    function getMaxResourceIndex() {
        const defer = $.Deferred();
        Office.context.document.getMaxResourceIndexAsync(
            function (result) {
                if (result.status === Office.AsyncResultStatus.Failed) {
                    onError(result.error);
                }
                else {
                    defer.resolve(result.value);
                }
            }
        );
        return defer.promise();
    }

    // Get each resource GUID, and then display the GUIDs in the add-in.
    // There is no 0 index for resources, so start with index 1.
    function getResourceGuids(maxResourceIndex) {
        const defer = $.Deferred();
        for (let i = 1; i <= maxResourceIndex; i++) {
            getResourceGuid(i);
        }
        return defer.promise();
        function getResourceGuid(index) {
            Office.context.document.getResourceByIndexAsync(index,
                function (result) {
                    if (result.status === Office.AsyncResultStatus.Succeeded) {
                        resourceGuids.push(result.value);
                        if (index == maxResourceIndex) {
                            defer.resolve();
                            $('#message').html(resourceGuids.toString());
                        }
                    }
                    else {
                        onError(result.error);
                    }
                }
            );
        }
    }
    function onError(error) {
        app.showNotification(error.name + ' ' + error.code + ': ' + error.message);
    }
})();

getMaxTaskIndexAsync(options, callback)

Project documents only. Get the maximum index of the collection of tasks in the current project.

Important: This API works only in Project on Windows desktop.

getMaxTaskIndexAsync(options?: Office.AsyncContextOptions, callback?: (result: AsyncResult<number>) => void): void;

Parameters

options
Office.AsyncContextOptions

Provides an option for preserving context data of any type, unchanged, for use in a callback.

callback

(result: Office.AsyncResult<number>) => void

Optional. A function that is invoked when the callback returns, whose only parameter is of type Office.AsyncResult. The value property of the result is the highest index number in the current project's task collection.

Returns

void

getMaxTaskIndexAsync(callback)

Project documents only. Get the maximum index of the collection of tasks in the current project.

Important: This API works only in Project on Windows desktop.

getMaxTaskIndexAsync(callback?: (result: AsyncResult<number>) => void): void;

Parameters

callback

(result: Office.AsyncResult<number>) => void

Optional. A function that is invoked when the callback returns, whose only parameter is of type Office.AsyncResult. The value property of the result is the highest index number in the current project's task collection.

Returns

void

Examples

// The following code example calls getMaxTaskIndexAsync to get the maximum index
// of the collection of tasks in the current project. Then it uses the returned value
// with the getTaskByIndexAsync method to get each task GUID.
// The example assumes your add-in has a reference to the jQuery library and that the
// following page controls are defined in the content div in the page body:
// <input id="get-info" type="button" value="Get info" /><br />
// <span id="message"></span>

(function () {
    "use strict";
    const taskGuids = [];

    // The initialize function must be run each time a new page is loaded.
    Office.initialize = function (reason) {
        $(document).ready(function () {

            // After the DOM is loaded, add-in-specific code can run.
            app.initialize();
            $('#get-info').on("click", getTaskInfo);
        });
    };

    // Get the maximum task index, and then get the task GUIDs.
    function getTaskInfo() {
        getMaxTaskIndex().then(
            function (data) {
                getTaskGuids(data);
            }
        );
    }

    // Get the maximum index of the tasks for the current project.
    function getMaxTaskIndex() {
        const defer = $.Deferred();
        Office.context.document.getMaxTaskIndexAsync(
            function (result) {
                if (result.status === Office.AsyncResultStatus.Failed) {
                    onError(result.error);
                }
                else {
                    defer.resolve(result.value);
                }
            }
        );
        return defer.promise();
    }

    // Get each task GUID, and then display the GUIDs in the add-in.
    function getTaskGuids(maxTaskIndex) {
        const defer = $.Deferred();
        for (let i = 0; i <= maxTaskIndex; i++) {
            getTaskGuid(i);
        }
        return defer.promise();
        function getTaskGuid(index) {
            Office.context.document.getTaskByIndexAsync(index,
                function (result) {
                    if (result.status === Office.AsyncResultStatus.Succeeded) {
                        taskGuids.push(result.value);
                        if (index == maxTaskIndex) {
                            defer.resolve();
                            $('#message').html(taskGuids.toString());
                        }
                    }
                    else {
                        onError(result.error);
                    }
                }
            );
        }
    }
    function onError(error) {
        app.showNotification(error.name + ' ' + error.code + ': ' + error.message);
    }
})();

getProjectFieldAsync(fieldId, options, callback)

Project documents only. Get Project field (e.g., ProjectWebAccessURL).

getProjectFieldAsync(fieldId: number, options?: Office.AsyncContextOptions, callback?: (result: AsyncResult<any>) => void): void;

Parameters

fieldId

number

Project level fields.

options
Office.AsyncContextOptions

Provides an option for preserving context data of any type, unchanged, for use in a callback.

callback

(result: Office.AsyncResult<any>) => void

Optional. A function that is invoked when the callback returns, whose only parameter is of type Office.AsyncResult. The value property of the result contains the fieldValue property, which represents the value of the specified field.

Returns

void

getProjectFieldAsync(fieldId, callback)

Project documents only. Get Project field (e.g., ProjectWebAccessURL).

getProjectFieldAsync(fieldId: number, callback?: (result: AsyncResult<any>) => void): void;

Parameters

fieldId

number

Project level fields.

callback

(result: Office.AsyncResult<any>) => void

Optional. A function that is invoked when the callback returns, whose only parameter is of type Office.AsyncResult. The value property of the result contains the fieldValue property, which represents the value of the specified field.

Returns

void

Examples

// The following code example gets the values of three specified fields for the active project, 
// and then displays the values in the add-in.
// The example calls getProjectFieldAsync recursively, after the previous call returns successfully.
// It also tracks the calls to determine when all calls are sent.
// The example assumes your add-in has a reference to the jQuery library and that the 
// following page control is defined in the content div in the page body:
// <span id="message"></span>

(function () {
    "use strict";

    // The initialize function must be run each time a new page is loaded.
    Office.initialize = function (reason) {
        $(document).ready(function () {

            // Get information for the active project.
            getProjectInformation();
        });
    };

    // Get the specified fields for the active project.
    function getProjectInformation() {
        const fields =
            [Office.ProjectProjectFields.Start, 
             Office.ProjectProjectFields.Finish, 
             Office.ProjectProjectFields.GUID];
        const fieldValues = ['Start: ', 'Finish: ', 'GUID: '];
        let index = 0; 
        getField();

        // Get each field, and then display the field values in the add-in.
        function getField() {
            if (index == fields.length) {
                let output = '';
                for (let i = 0; i < fieldValues.length; i++) {
                    output += fieldValues[i] + '<br />';
                }
                $('#message').html(output);
            }
            else {
                Office.context.document.getProjectFieldAsync(
                    fields[index],
                    function (result) {

                        // If the call is successful, get the field value and then get the next field.
                        if (result.status === Office.AsyncResultStatus.Succeeded) {
                            fieldValues[index] += result.value.fieldValue;
                            getField(index++);
                        }
                        else {
                            onError(result.error);
                        }
                    }
                );
            }
        }
    }

    function onError(error) {
        $('#message').html(error.name + ' ' + error.code + ': ' + error.message);
    }
})();

getResourceByIndexAsync(resourceIndex, options, callback)

Project documents only. Get the GUID of the resource that has the specified index in the resource collection.

Important: This API works only in Project on Windows desktop.

getResourceByIndexAsync(resourceIndex: number, options?: Office.AsyncContextOptions, callback?: (result: AsyncResult<string>) => void): void;

Parameters

resourceIndex

number

The index of the resource in the collection of resources for the project.

options
Office.AsyncContextOptions

Provides an option for preserving context data of any type, unchanged, for use in a callback.

callback

(result: Office.AsyncResult<string>) => void

Optional. A function that is invoked when the callback returns, whose only parameter is of type Office.AsyncResult. The value property of the result is the GUID of the resource as a string.

Returns

void

getResourceByIndexAsync(resourceIndex, callback)

Project documents only. Get the GUID of the resource that has the specified index in the resource collection.

Important: This API works only in Project on Windows desktop.

getResourceByIndexAsync(resourceIndex: number, callback?: (result: AsyncResult<string>) => void): void;

Parameters

resourceIndex

number

The index of the resource in the collection of resources for the project.

callback

(result: Office.AsyncResult<string>) => void

Optional. A function that is invoked when the callback returns, whose only parameter is of type Office.AsyncResult. The value property of the result is the GUID of the resource as a string.

Returns

void

Examples

// The following code example calls getMaxResourceIndexAsync to get the maximum index in the project's resource
// collection, and then calls getResourceByIndexAsync to get the GUID for each resource.
// The example assumes that your add-in has a reference to the jQuery library and that the following 
// page controls are defined in the content div in the page body:
// <input id="get-info" type="button" value="Get info" /><br />
// <span id="message"></span>

(function () {
    "use strict";
    const resourceGuids = [];

    // The initialize function must be run each time a new page is loaded.
    Office.initialize = function (reason) {
        $(document).ready(function () {

            // After the DOM is loaded, add-in-specific code can run.
            app.initialize();
            $('#get-info').on("click", getResourceInfo);
        });
    };

    // Get the maximum resource index, and then get the resource GUIDs.
    function getResourceInfo() {
        getMaxResourceIndex().then(
            function (data) {
                getResourceGuids(data);
            }
        );
    }

    // Get the maximum index of the resources for the current project.
    function getMaxResourceIndex() {
        const defer = $.Deferred();
        Office.context.document.getMaxResourceIndexAsync(
            function (result) {
                if (result.status === Office.AsyncResultStatus.Failed) {
                    onError(result.error);
                }
                else {
                    defer.resolve(result.value);
                }
            }
        );
        return defer.promise();
    }

    // Get each resource GUID, and then display the GUIDs in the add-in.
    // There is no 0 index for resources, so start with index 1.
    function getResourceGuids(maxResourceIndex) {
        const defer = $.Deferred();
        for (let i = 1; i <= maxResourceIndex; i++) {
            getResourceGuid(i);
        }
        return defer.promise();
        function getResourceGuid(index) {
            Office.context.document.getResourceByIndexAsync(index,
                function (result) {
                    if (result.status === Office.AsyncResultStatus.Succeeded) {
                        resourceGuids.push(result.value);
                        if (index == maxResourceIndex) {
                            defer.resolve();
                            $('#message').html(resourceGuids.toString());
                        }
                    }
                    else {
                        onError(result.error);
                    }
                }
            );
        }
    }
    function onError(error) {
        app.showNotification(error.name + ' ' + error.code + ': ' + error.message);
    }
})();

getResourceFieldAsync(resourceId, fieldId, options, callback)

Project documents only. Get resource field for provided resource ID. (e.g., ResourceName)

getResourceFieldAsync(resourceId: string, fieldId: number, options?: Office.AsyncContextOptions, callback?: (result: AsyncResult<string>) => void): void;

Parameters

resourceId

string

Either a string or value of the Resource ID.

fieldId

number

Resource Fields.

options
Office.AsyncContextOptions

Provides an option for preserving context data of any type, unchanged, for use in a callback.

callback

(result: Office.AsyncResult<string>) => void

Optional. A function that is invoked when the callback returns, whose only parameter is of type Office.AsyncResult. The value property of the result is the GUID of the resource as a string.

Returns

void

getResourceFieldAsync(resourceId, fieldId, callback)

Project documents only. Get resource field for provided resource ID. (e.g., ResourceName)

getResourceFieldAsync(resourceId: string, fieldId: number, callback?: (result: AsyncResult<string>) => void): void;

Parameters

resourceId

string

Either a string or value of the Resource ID.

fieldId

number

Resource Fields.

callback

(result: Office.AsyncResult<string>) => void

Optional. A function that is invoked when the callback returns, whose only parameter is of type Office.AsyncResult. The value property of the result is the GUID of the resource as a string.

Returns

void

Examples

// The following code example calls getSelectedResourceAsync to get the GUID of the resource
// that's currently selected in a resource view. Then it gets three resource field values by calling 
// getResourceFieldAsync recursively.
// The example assumes your add-in has a reference to the jQuery library and that the following 
// page controls are defined in the content div in the page body:
// <input id="get-info" type="button" value="Get info" /><br />
// <span id="message"></span>

(function () {
    "use strict";

    // The initialize function must be run each time a new page is loaded.
    Office.initialize = function (reason) {
        $(document).ready(function () {

            // After the DOM is loaded, add-in-specific code can run.
            $('#get-info').on("click", getResourceInfo);
        });
    };

    // Get the GUID of the resource and then get the resource fields.
    function getResourceInfo() {
        getResourceGuid().then(
            function (data) {
                getResourceFields(data);
            }
        );
    }

    // Get the GUID of the selected resource.
    function getResourceGuid() {
        const defer = $.Deferred();
        Office.context.document.getSelectedResourceAsync(
            function (result) {
                if (result.status === Office.AsyncResultStatus.Failed) {
                    onError(result.error);
                }
                else {
                    defer.resolve(result.value);
                }
            }
        );
        return defer.promise();
    }

    // Get the specified fields for the selected resource.
    function getResourceFields(resourceGuid) {
        const targetFields =
            [Office.ProjectResourceFields.Name,
             Office.ProjectResourceFields.Units, 
             Office.ProjectResourceFields.BaseCalendar];
        const fieldValues = ['Name: ', 'Units: ', 'Base calendar: '];
        let index = 0; 
        getField();

        // Get each field, and then display the field values in the add-in.
        function getField() {
            if (index == targetFields.length) {
                let output = '';
                for (let i = 0; i < fieldValues.length; i++) {
                    output += fieldValues[i] + '<br />';
                }
                $('#message').html(output);
            }

            // If the call is successful, get the field value and then get the next field.
            else {
                Office.context.document.getResourceFieldAsync(
                    resourceGuid,
                    targetFields[index],
                    function (result) {
                        if (result.status === Office.AsyncResultStatus.Succeeded) {
                            fieldValues[index] += result.value.fieldValue;
                            getField(index++);
                        }
                        else {
                            onError(result.error);
                        }
                    }
                );
            }
        }
    }

    function onError(error) {
        $('#message').html(error.name + ' ' + error.code + ': ' + error.message);
    }
})();

getSelectedDataAsync(coercionType, options, callback)

Reads the data contained in the current selection in the document.

getSelectedDataAsync<T>(coercionType: Office.CoercionType, options?: GetSelectedDataOptions, callback?: (result: AsyncResult<T>) => void): void;

Parameters

coercionType
Office.CoercionType

The type of data structure to return. See the Remarks section for each application's supported coercion types.

options
Office.GetSelectedDataOptions

Provides options for customizing what data is returned and how it is formatted.

callback

(result: Office.AsyncResult<T>) => void

Optional. A function that is invoked when the callback returns, whose only parameter is of type Office.AsyncResult. The value property of the result is the data in the current selection. This is returned in the data structure or format you specified with the coercionType parameter. (See Remarks for more information about data coercion.)

Returns

void

Remarks

Requirement sets:

In the callback function that is passed to the getSelectedDataAsync method, you can use the properties of the AsyncResult object to return the following information.

Property Use
AsyncResult.value Always returns undefined because there's no object or data to retrieve.
AsyncResult.status Determine the success or failure of the operation.
AsyncResult.error Access an Error object that provides error information if the operation failed.
AsyncResult.asyncContext Define an item of any type that's returned in the AsyncResult object without being altered.

The possible values for the Office.CoercionType parameter vary by the Office application.

CoercionType Supported applications
Office.CoercionType.Html
  • Word
Office.CoercionType.Matrix (array of arrays)
  • Excel
  • Word
Office.CoercionType.Ooxml (Office Open XML)
  • Word
Office.CoercionType.SlideRange
  • PowerPoint
Office.CoercionType.Table (TableData object)
  • Excel
  • Word
Office.CoercionType.Text (string)
  • Excel
  • PowerPoint
  • Project
  • Word
Office.CoercionType.XmlSvg
  • Excel on Windows and on Mac

Examples

// The following example uses the getSelectedDataAsync method of the Document object to retrieve the
// user's current selection as text, and then display it in the add-in's page.

// Displays the user's current selection.
function showSelection() {
    Office.context.document.getSelectedDataAsync(
        Office.CoercionType.Text,
        {
            valueFormat: Office.ValueFormat.Unformatted,
            filterType: Office.FilterType.All
        },
        (result) => {
            const dataValue = result.value;
            write('Selected data is: ' + dataValue);
        }
    );
}
// Function that writes to a div with id='message' on the page.
function write(message){
    document.getElementById('message').innerText += message; 
}
// To read the value of the current selection, you need to write a callback function that reads the selection.
// The following example shows how to:
// 1. Pass an anonymous callback function that reads the value of the current selection
//    to the callback parameter of the getSelectedDataAsync method.
// 2. Read the selection as text, unformatted, and not filtered.
// 3. Display the value on the add-in's page.
function getText() {
    Office.context.document.getSelectedDataAsync(
        Office.CoercionType.Text,
        {
            valueFormat: Office.ValueFormat.Unformatted,
            filterType: Office.FilterType.All
        },
        (asyncResult) => {
            const error = asyncResult.error;
            if (asyncResult.status === Office.AsyncResultStatus.Failed) {
                write(error.name + ": " + error.message);
            } 
            else {
                // Get selected data.
                const dataValue = asyncResult.value; 
                write('Selected data is ' + dataValue);
            }
        }
    );
}

// Function that writes to a div with id='message' on the page.
function write(message){
    document.getElementById('message').innerText += message; 
}
// The following code example gets the values of the selected cells. It uses the optional
// asyncContext parameter to pass some text to the callback function.
// The example assumes your add-in has a reference to the jQuery library and that the
// following page controls are defined in the content div in the page body:
// <input id="get-info" type="button" value="Get info" /><br />
// <span id="message"></span>

// The onReady function must be run each time a new page is loaded.
Office.onReady(() => {
    $(document).ready(() => {
        // After the DOM is loaded, add-in-specific code can run.
        $('#get-info').on("click", getSelectedText);
    });
});

// Gets the text from the selected cells in the document, and displays it in the add-in.
function getSelectedText() {
    Office.context.document.getSelectedDataAsync(
        Office.CoercionType.Text,
        { asyncContext: "Some related info" },
        (result) => {
            if (result.status === Office.AsyncResultStatus.Failed) {
                onError(result.error);
            }
            else {
                const output = String.format(
                    'Selected text: {0}<br/>Passed info: {1}',
                    result.value, result.asyncContext);
                $('#message').html(output);
            }
        }
    );
}

function onError(error) {
    $('#message').html(error.name + ' ' + error.code + ': ' + error.message);
}

getSelectedDataAsync(coercionType, callback)

Reads the data contained in the current selection in the document.

getSelectedDataAsync<T>(coercionType: Office.CoercionType, callback?: (result: AsyncResult<T>) => void): void;

Parameters

coercionType
Office.CoercionType

The type of data structure to return. See the Remarks section for each application's supported coercion types.

callback

(result: Office.AsyncResult<T>) => void

Optional. A function that is invoked when the callback returns, whose only parameter is of type Office.AsyncResult. The value property of the result is the data in the current selection. This is returned in the data structure or format you specified with the coercionType parameter. (See Remarks for more information about data coercion.)

Returns

void

Remarks

Requirement sets:

In the callback function that is passed to the getSelectedDataAsync method, you can use the properties of the AsyncResult object to return the following information.

Property Use
AsyncResult.value Always returns undefined because there's no object or data to retrieve.
AsyncResult.status Determine the success or failure of the operation.
AsyncResult.error Access an Error object that provides error information if the operation failed.
AsyncResult.asyncContext Define an item of any type that's returned in the AsyncResult object without being altered.

The possible values for the Office.CoercionType parameter vary by the Office application.

CoercionType Supported applications
Office.CoercionType.Html
  • Word
Office.CoercionType.Matrix (array of arrays)
  • Excel
  • Word
Office.CoercionType.Ooxml (Office Open XML)
  • Word
Office.CoercionType.SlideRange
  • PowerPoint
Office.CoercionType.Table (TableData object)
  • Excel
  • Word
Office.CoercionType.Text (string)
  • Excel
  • PowerPoint
  • Project
  • Word
Office.CoercionType.XmlSvg
  • Excel on Windows and on Mac

getSelectedResourceAsync(options, callback)

Project documents only. Get the current selected Resource's ID.

getSelectedResourceAsync(options?: Office.AsyncContextOptions, callback?: (result: AsyncResult<string>) => void): void;

Parameters

options
Office.AsyncContextOptions

Provides an option for preserving context data of any type, unchanged, for use in a callback.

callback

(result: Office.AsyncResult<string>) => void

Optional. A function that is invoked when the callback returns, whose only parameter is of type Office.AsyncResult. The value property of the result is the GUID of the resource as a string.

Returns

void

getSelectedResourceAsync(callback)

Project documents only. Get the current selected Resource's ID.

getSelectedResourceAsync(callback?: (result: AsyncResult<string>) => void): void;

Parameters

callback

(result: Office.AsyncResult<string>) => void

Optional. A function that is invoked when the callback returns, whose only parameter is of type Office.AsyncResult. The value property of the result is the GUID of the resource as a string.

Returns

void

Examples

// The following code example calls getSelectedResourceAsync to get the GUID of the resource that's 
// currently selected in a resource view. Then it gets three resource field values by calling 
// getResourceFieldAsync recursively.
// The example assumes your add-in has a reference to the jQuery library and that the following page controls are
// defined in the content div in the page body:
// <input id="get-info" type="button" value="Get info" /><br />
// <span id="message"></span>

(function () {
    "use strict";

    // The initialize function must be run each time a new page is loaded.
    Office.initialize = function (reason) {
        $(document).ready(function () {

            // After the DOM is loaded, add-in-specific code can run.
            $('#get-info').on("click", getResourceInfo);
        });
    };

    // Get the GUID of the resource and then get the resource fields.
    function getResourceInfo() {
        getResourceGuid().then(
            function (data) {
                getResourceFields(data);
            }
        );
    }

    // Get the GUID of the selected resource.
    function getResourceGuid() {
        const defer = $.Deferred();
        Office.context.document.getSelectedResourceAsync(
            function (result) {
                if (result.status === Office.AsyncResultStatus.Failed) {
                    onError(result.error);
                }
                else {
                    defer.resolve(result.value);
                }
            }
        );
        return defer.promise();
    }

    // Get the specified fields for the selected resource.
    function getResourceFields(resourceGuid) {
        const targetFields =
            [Office.ProjectResourceFields.Name,
             Office.ProjectResourceFields.Units, 
             Office.ProjectResourceFields.BaseCalendar];
        const fieldValues = ['Name: ', 'Units: ', 'Base calendar: '];
        let index = 0; 
        getField();

        // Get each field, and then display the field values in the add-in.
        function getField() {
            if (index == targetFields.length) {
                let output = '';
                for (let i = 0; i < fieldValues.length; i++) {
                    output += fieldValues[i] + '<br />';
                }
                $('#message').html(output);
            }

            // If the call is successful, get the field value and then get the next field.
            else {
                Office.context.document.getResourceFieldAsync(
                    resourceGuid,
                    targetFields[index],
                    function (result) {
                        if (result.status === Office.AsyncResultStatus.Succeeded) {
                            fieldValues[index] += result.value.fieldValue;
                            getField(index++);
                        }
                        else {
                            onError(result.error);
                        }
                    }
                );
            }
        }
    }

    function onError(error) {
        $('#message').html(error.name + ' ' + error.code + ': ' + error.message);
    }
})();

getSelectedTaskAsync(options, callback)

Project documents only. Get the current selected Task's ID.

getSelectedTaskAsync(options?: Office.AsyncContextOptions, callback?: (result: AsyncResult<string>) => void): void;

Parameters

options
Office.AsyncContextOptions

Provides an option for preserving context data of any type, unchanged, for use in a callback.

callback

(result: Office.AsyncResult<string>) => void

Optional. A function that is invoked when the callback returns, whose only parameter is of type Office.AsyncResult. The value property of the result is the GUID of the resource as a string.

Returns

void

getSelectedTaskAsync(callback)

Project documents only. Get the current selected Task's Id.

getSelectedTaskAsync(callback?: (result: AsyncResult<string>) => void): void;

Parameters

callback

(result: Office.AsyncResult<string>) => void

Optional. A function that is invoked when the callback returns, whose only parameter is of type Office.AsyncResult. The value property of the result is the GUID of the resource as a string.

Returns

void

Examples

// The following code example calls getSelectedTaskAsync to get the GUID of the task that's currently
// selected in a task view. Then it gets task properties by calling getTaskAsync.
// The example assumes your add-in has a reference to the jQuery library and that the following page
// controls are defined in the content div in the page body:
// <input id="get-info" type="button" value="Get info" /><br />
// <span id="message"></span>

(function () {
    "use strict";

    // The initialize function must be run each time a new page is loaded.
    Office.initialize = function (reason) {
        $(document).ready(function () {

            // After the DOM is loaded, add-in-specific code can run.
            $('#get-info').on("click", getTaskInfo);
        });
    };

    // // Get the GUID of the task, and then get local task properties.
    function getTaskInfo() {
        getTaskGuid().then(
            function (data) {
                getTaskProperties(data);
            }
        );
    }

    // Get the GUID of the selected task.
    function getTaskGuid() {
        const defer = $.Deferred();
        Office.context.document.getSelectedTaskAsync(
            function (result) {
                if (result.status === Office.AsyncResultStatus.Failed) {
                    onError(result.error);
                }
                else {
                    defer.resolve(result.value);
                }
            }
        );
        return defer.promise();
    }

    // Get local properties for the selected task, and then display it in the add-in.
    function getTaskProperties(taskGuid) {
        Office.context.document.getTaskAsync(
            taskGuid,
            function (result) {
                if (result.status === Office.AsyncResultStatus.Failed) {
                    onError(result.error);
                }
                else {
                    const taskInfo = result.value;
                    const output = String.format(
                        'Name: {0}<br/>GUID: {1}<br/>SharePoint task ID: {2}<br/>Resource names: {3}',
                        taskInfo.taskName, taskGuid, taskInfo.wssTaskId, taskInfo.resourceNames);
                    $('#message').html(output);
                }
            }
        );
    }

    function onError(error) {
        $('#message').html(error.name + ' ' + error.code + ': ' + error.message);
    }
})();

getSelectedViewAsync(options, callback)

Project documents only. Get the current selected View Type (e.g., Gantt) and View Name.

getSelectedViewAsync(options?: Office.AsyncContextOptions, callback?: (result: AsyncResult<any>) => void): void;

Parameters

options
Office.AsyncContextOptions

Provides an option for preserving context data of any type, unchanged, for use in a callback.

callback

(result: Office.AsyncResult<any>) => void

Optional. A function that is invoked when the callback returns, whose only parameter is of type Office.AsyncResult. The value property of the result contains the following properties: viewName - The name of the view, as a ProjectViewTypes constant. viewType - The type of view, as the integer value of a ProjectViewTypes constant.

Returns

void

getSelectedViewAsync(callback)

Project documents only. Get the current selected View Type (e.g., Gantt) and View Name.

getSelectedViewAsync(callback?: (result: AsyncResult<any>) => void): void;

Parameters

callback

(result: Office.AsyncResult<any>) => void

Optional. A function that is invoked when the callback returns, whose only parameter is of type Office.AsyncResult. The value property of the result contains the following properties: viewName - The name of the view, as a ProjectViewTypes constant. viewType - The type of view, as the integer value of a ProjectViewTypes constant.

Returns

void

Examples

// The following code example calls adds a ViewSelectionChanged event handler that
// calls getSelectedViewAsync to get the name and type of the active view in the document.
// The example assumes your add-in has a reference to the jQuery library and that
// the following page control is defined in the content div in the page body:
// <span id="message"></span>

(function () {
    "use strict";

    // The initialize function must be run each time a new page is loaded.
    Office.initialize = function (reason) {
        $(document).ready(function () {

            // After the DOM is loaded, add-in-specific code can run.
            Office.context.document.addHandlerAsync(
                Office.EventType.ViewSelectionChanged,
                getActiveView);
            getActiveView();
        });
    };

    // Get the active view's name and type.
    function getActiveView() {
        Office.context.document.getSelectedViewAsync(
            function (result) {
                if (result.status === Office.AsyncResultStatus.Failed) {
                    onError(result.error);
                }
                else {
                    const output = String.format(
                        'View name: {0}<br/>View type: {1}',
                        result.value.viewName, viewType);
                    $('#message').html(output);
                }
            }
        );
    }

    function onError(error) {
        $('#message').html(error.name + ' ' + error.code + ': ' + error.message);
    }
})();

getTaskAsync(taskId, options, callback)

Project documents only. Get the Task Name, WSS Task ID, and ResourceNames for given taskId.

getTaskAsync(taskId: string, options?: Office.AsyncContextOptions, callback?: (result: AsyncResult<any>) => void): void;

Parameters

taskId

string

Either a string or value of the Task ID.

options
Office.AsyncContextOptions

Provides an option for preserving context data of any type, unchanged, for use in a callback.

callback

(result: Office.AsyncResult<any>) => void

Optional. A function that is invoked when the callback returns, whose only parameter is of type Office.AsyncResult. The value property of the result contains the following properties: taskName - The name of the task. wssTaskId - The ID of the task in the synchronized SharePoint task list. If the project is not synchronized with a SharePoint task list, the value is 0. resourceNames - The comma-separated list of the names of resources that are assigned to the task.

Returns

void

getTaskAsync(taskId, callback)

Project documents only. Get the Task Name, WSS Task ID, and ResourceNames for given taskId.

getTaskAsync(taskId: string, callback?: (result: AsyncResult<any>) => void): void;

Parameters

taskId

string

Either a string or value of the Task ID.

callback

(result: Office.AsyncResult<any>) => void

Optional. A function that is invoked when the callback returns, whose only parameter is of type Office.AsyncResult. The value property of the result contains the following properties: taskName - The name of the task. wssTaskId - The ID of the task in the synchronized SharePoint task list. If the project is not synchronized with a SharePoint task list, the value is 0. resourceNames - The comma-separated list of the names of resources that are assigned to the task.

Returns

void

Examples

// The following code example calls getSelectedTaskAsync to get the task GUID of the currently
// selected task. Then it calls getTaskAsync to get the properties for the task that are
// available from the JavaScript API for Office.
// The example assumes your add-in has a reference to the jQuery library and that the
// following page controls are defined in the content div in the page body:
// <input id="get-info" type="button" value="Get info" /><br />
// <span id="message"></span>

(function () {
    "use strict";

    // The initialize function must be run each time a new page is loaded.
    Office.initialize = function (reason) {
        $(document).ready(function () {

            // After the DOM is loaded, add-in-specific code can run.
            $('#get-info').on("click", getTaskInfo);
        });
    };

    // Get the GUID of the task, and then get local task properties.
    function getTaskInfo() {
        getTaskGuid().then(
            function (data) {
                getTaskProperties(data);
            }
        );
    }

    // Get the GUID of the selected task.
    function getTaskGuid() {
        const defer = $.Deferred();
        Office.context.document.getSelectedTaskAsync(
            function (result) {
                if (result.status === Office.AsyncResultStatus.Failed) {
                    onError(result.error);
                }
                else {
                    defer.resolve(result.value);
                }
            }
        );
        return defer.promise();
    }

    // Get local properties for the selected task, and then display it in the add-in.
    function getTaskProperties(taskGuid) {
        Office.context.document.getTaskAsync(
            taskGuid,
            function (result) {
                if (result.status === Office.AsyncResultStatus.Failed) {
                    onError(result.error);
                }
                else {
                    const taskInfo = result.value;
                    const output = String.format(
                        'Name: {0}<br/>GUID: {1}<br/>SharePoint task ID: {2}<br/>Resource names: {3}',
                        taskInfo.taskName, taskGuid, taskInfo.wssTaskId, taskInfo.resourceNames);
                    $('#message').html(output);
                }
            }
        );
    }

    function onError(error) {
        $('#message').html(error.name + ' ' + error.code + ': ' + error.message);
    }
})();

getTaskByIndexAsync(taskIndex, options, callback)

Project documents only. Get the GUID of the task that has the specified index in the task collection.

Important: This API works only in Project on Windows desktop.

getTaskByIndexAsync(taskIndex: number, options?: Office.AsyncContextOptions, callback?: (result: AsyncResult<string>) => void): void;

Parameters

taskIndex

number

The index of the task in the collection of tasks for the project.

options
Office.AsyncContextOptions

Provides an option for preserving context data of any type, unchanged, for use in a callback.

callback

(result: Office.AsyncResult<string>) => void

Optional. A function that is invoked when the callback returns, whose only parameter is of type Office.AsyncResult. The value property of the result is the GUID of the task as a string.

Returns

void

getTaskByIndexAsync(taskIndex, callback)

Project documents only. Get the GUID of the task that has the specified index in the task collection.

Important: This API works only in Project on Windows desktop.

getTaskByIndexAsync(taskIndex: number, callback?: (result: AsyncResult<string>) => void): void;

Parameters

taskIndex

number

The index of the task in the collection of tasks for the project.

callback

(result: Office.AsyncResult<string>) => void

Optional. A function that is invoked when the callback returns, whose only parameter is of type Office.AsyncResult. The value property of the result is the GUID of the task as a string.

Returns

void

Examples

// The following code example calls getMaxTaskIndexAsync to get the
// maximum index in the project's task collection, and then
// calls getTaskByIndexAsync to get the GUID for each task.
// The example assumes that your add-in has a reference to the
// jQuery library and that the following page controls are defined
// in the content div in the page body:
// <input id="get-info" type="button" value="Get info" /><br />
// <span id="message"></span>

(function () {
    "use strict";
    const taskGuids = [];

    // The initialize function must be run each time a new page is loaded.
    Office.initialize = function (reason) {
        $(document).ready(function () {

            // After the DOM is loaded, add-in-specific code can run.
            app.initialize();
            $('#get-info').on("click", getTaskInfo);
        });
    };

    // Get the maximum task index, and then get the task GUIDs.
    function getTaskInfo() {
        getMaxTaskIndex().then(
            function (data) {
                getTaskGuids(data);
            }
        );
    }

    // Get the maximum index of the tasks for the current project.
    function getMaxTaskIndex() {
        const defer = $.Deferred();
        Office.context.document.getMaxTaskIndexAsync(
            function (result) {
                if (result.status === Office.AsyncResultStatus.Failed) {
                    onError(result.error);
                }
                else {
                    defer.resolve(result.value);
                }
            }
        );
        return defer.promise();
    }

    // Get each task GUID, and then display the GUIDs in the add-in.
    function getTaskGuids(maxTaskIndex) {
        const defer = $.Deferred();
        for (let i = 0; i <= maxTaskIndex; i++) {
            getTaskGuid(i);
        }
        return defer.promise();
        function getTaskGuid(index) {
            Office.context.document.getTaskByIndexAsync(index,
                function (result) {
                    if (result.status === Office.AsyncResultStatus.Succeeded) {
                        taskGuids.push(result.value);
                        if (index == maxTaskIndex) {
                            defer.resolve();
                            $('#message').html(taskGuids.toString());
                        }
                    }
                    else {
                        onError(result.error);
                    }
                }
            );
        }
    }
    function onError(error) {
        app.showNotification(error.name + ' ' + error.code + ': ' + error.message);
    }
})();

getTaskFieldAsync(taskId, fieldId, options, callback)

Project documents only. Get task field for provided task ID. (e.g., StartDate).

getTaskFieldAsync(taskId: string, fieldId: number, options?: Office.AsyncContextOptions, callback?: (result: AsyncResult<any>) => void): void;

Parameters

taskId

string

Either a string or value of the Task ID.

fieldId

number

Task Fields.

options
Office.AsyncContextOptions

Provides an option for preserving context data of any type, unchanged, for use in a callback.

callback

(result: Office.AsyncResult<any>) => void

Optional. A function that is invoked when the callback returns, whose only parameter is of type Office.AsyncResult. The value property of the result contains the fieldValue property, which represents the value of the specified field.

Returns

void

getTaskFieldAsync(taskId, fieldId, callback)

Project documents only. Get task field for provided task ID. (e.g., StartDate).

getTaskFieldAsync(taskId: string, fieldId: number, callback?: (result: AsyncResult<any>) => void): void;

Parameters

taskId

string

Either a string or value of the Task ID.

fieldId

number

Task Fields.

callback

(result: Office.AsyncResult<any>) => void

Optional. A function that is invoked when the callback returns, whose only parameter is of type Office.AsyncResult. The value property of the result contains the fieldValue property, which represents the value of the specified field.

Returns

void

Examples

// The following code example calls getSelectedTaskAsync to get the GUID of the task that's currently
// selected in a task view. Then it gets two task field values by calling getTaskFieldAsync recursively.
// The example assumes your add-in has a reference to the jQuery library and that the following page
// controls are defined in the content div in the page body:
// <input id="get-info" type="button" value="Get info" /><br />
// <span id="message"></span>

(function () {
    "use strict";

    // The initialize function must be run each time a new page is loaded.
    Office.initialize = function (reason) {
        $(document).ready(function () {
            
            // After the DOM is loaded, add-in-specific code can run.
            $('#get-info').on("click", getTaskInfo);
        });
    };

    // Get the GUID of the task, and then get the task fields.
    function getTaskInfo() {
        getTaskGuid().then(
            function (data) {
                getTaskFields(data);
            }
        );
    }

    // Get the GUID of the selected task.
    function getTaskGuid() {
        const defer = $.Deferred();
        Office.context.document.getSelectedTaskAsync(
            function (result) {
                if (result.status === Office.AsyncResultStatus.Failed) {
                    onError(result.error);
                }
                else {
                    defer.resolve(result.value);
                }
            }
        );
        return defer.promise();
    }

    // Get the specified fields for the selected task.
    function getTaskFields(taskGuid) {
        let output = '';
        const targetFields = [Office.ProjectTaskFields.Priority, Office.ProjectTaskFields.PercentComplete];
        const fieldValues = ['Priority: ', '% Complete: '];
        let index = 0;
        getField();

        // Get each field, and then display the field values in the add-in.
        function getField() {
            if (index == targetFields.length) {
                for (let i = 0; i < fieldValues.length; i++) {
                    output += fieldValues[i] + '<br />';
                }
                $('#message').html(output);
            }

            // Get the field value. If the call is successful, then get the next field.
            else {
                Office.context.document.getTaskFieldAsync(
                    taskGuid,
                    targetFields[index],
                    function (result) {
                        if (result.status === Office.AsyncResultStatus.Succeeded) {
                            fieldValues[index] += result.value.fieldValue;
                            getField(index++);
                        }
                        else {
                            onError(result.error);
                        }
                    }
                );
            }
        }
    }

    function onError(error) {
        $('#message').html(error.name + ' ' + error.code + ': ' + error.message);
    }
})();

getWSSUrlAsync(options, callback)

Project documents only. Get the WSS Url and list name for the Tasks List, the MPP is synced too.

getWSSUrlAsync(options?: Office.AsyncContextOptions, callback?: (result: AsyncResult<any>) => void): void;

Parameters

options
Office.AsyncContextOptions

Provides an option for preserving context data of any type, unchanged, for use in a callback.

callback

(result: Office.AsyncResult<any>) => void

Optional. A function that is invoked when the callback returns, whose only parameter is of type Office.AsyncResult. The value property of the result contains the following properties: listName - the name of the synchronized SharePoint task list. serverUrl - the URL of the synchronized SharePoint task list.

Returns

void

getWSSUrlAsync(callback)

Project documents only. Get the WSS URL and list name for the Tasks List, the MPP is synced too.

getWSSUrlAsync(callback?: (result: AsyncResult<any>) => void): void;

Parameters

callback

(result: Office.AsyncResult<any>) => void

Optional. A function that is invoked when the callback returns, whose only parameter is of type Office.AsyncResult. The value property of the result contains the following properties: listName - the name of the synchronized SharePoint task list. serverUrl - the URL of the synchronized SharePoint task list.

Returns

void

goToByIdAsync(id, goToType, options, callback)

Goes to the specified object or location in the document.

goToByIdAsync(id: string | number, goToType: GoToType, options?: GoToByIdOptions, callback?: (result: AsyncResult<any>) => void): void;

Parameters

id

string | number

The identifier of the object or location to go to.

goToType
Office.GoToType

The type of the location to go to.

options
Office.GoToByIdOptions

Provides options for whether to select the location that is navigated to.

callback

(result: Office.AsyncResult<any>) => void

Optional. A function that is invoked when the callback returns, whose only parameter is of type Office.AsyncResult. The value property of the result is the current view.

Returns

void

Remarks

Requirement set: Not in a set

PowerPoint doesn't support the goToByIdAsync method in Master Views.

The behavior caused by the selectionMode option varies by Office application:

In Excel: Office.SelectionMode.Selected selects all content in the binding, or named item. Office.SelectionMode.None for text bindings, selects the cell; for matrix bindings, table bindings, and named items, selects the first data cell (not first cell in header row for tables).

In PowerPoint: Office.SelectionMode.Selected selects the slide title or first textbox on the slide. Office.SelectionMode.None doesn't select anything.

In Word: Office.SelectionMode.Selected selects all content in the binding. Office.SelectionMode.None for text bindings, moves the cursor to the beginning of the text; for matrix bindings and table bindings, selects the first data cell (not first cell in header row for tables).

goToByIdAsync(id, goToType, callback)

Goes to the specified object or location in the document.

goToByIdAsync(id: string | number, goToType: GoToType, callback?: (result: AsyncResult<any>) => void): void;

Parameters

id

string | number

The identifier of the object or location to go to.

goToType
Office.GoToType

The type of the location to go to.

callback

(result: Office.AsyncResult<any>) => void

Optional. A function that is invoked when the callback returns, whose only parameter is of type Office.AsyncResult. The value property of the result is the current view.

Returns

void

Remarks

Requirement set: Not in a set

PowerPoint doesn't support the goToByIdAsync method in Master Views.

The behavior caused by the selectionMode option varies by Office application:

In Excel: Office.SelectionMode.Selected selects all content in the binding, or named item. Office.SelectionMode.None for text bindings, selects the cell; for matrix bindings, table bindings, and named items, selects the first data cell (not first cell in header row for tables).

In PowerPoint: Office.SelectionMode.Selected selects the slide title or first textbox on the slide. Office.SelectionMode.None doesn't select anything.

In Word: Office.SelectionMode.Selected selects all content in the binding. Office.SelectionMode.None for text bindings, moves the cursor to the beginning of the text; for matrix bindings and table bindings, selects the first data cell (not first cell in header row for tables).

Examples

// Go to a binding by id (Word and Excel)
// The following example shows how to:
// 1. Create a table binding using the addFromSelectionAsync method as a sample binding to work with.
// 2. Specify that binding as the binding to go to.
// 3. Pass an anonymous callback function that returns the status of the operation
//    to the callback parameter of the goToByIdAsync method.
// 4. Display the value on the add-in's page.
function gotoBinding() {
    // Create a new table binding for the selected table.
    Office.context.document.bindings.addFromSelectionAsync("table",{ id: "MyTableBinding" }, function (asyncResult) {
    if (asyncResult.status == "failed") {
              showMessage("Action failed with error: " + asyncResult.error.message);
          }
          else {
              showMessage("Added new binding with type: " + asyncResult.value.type +" and id: " + asyncResult.value.id);
          }
    });

    // Go to binding by id.
    Office.context.document.goToByIdAsync("MyTableBinding", Office.GoToType.Binding, function (asyncResult) {
        if (asyncResult.status == "failed") {
            showMessage("Action failed with error: " + asyncResult.error.message);
        }
        else {
            showMessage("Navigation successful");
        }
    });
}

// Go to a table in a spreadsheet (Excel)
// The following example shows how to:
// 1. Specify a table by name as the table to go to.
// 2. Pass an anonymous callback function that returns the status of the operation
//    to the callback parameter of the goToByIdAsync method.
// 3. Display the value on the add-in's page.
function goToTable() {
    Office.context.document.goToByIdAsync("Table1", Office.GoToType.NamedItem, function (asyncResult) {
        if (asyncResult.status == "failed") {
            showMessage("Action failed with error: " + asyncResult.error.message);
        }
        else {
            showMessage("Navigation successful");
        }
    });
}

// Go to the currently selected slide by id (PowerPoint)
// The following example shows how to:
// 1. Get the id of the currently selected slides using the getSelectedDataAsync method.
// 2. Specify the returned id as the slide to go to.
// 3. Pass an anonymous callback function that returns the status of the operation
//    to the callback parameter of the goToByIdAsync method.
// 4. Display the value of the stringified JSON object returned by asyncResult.value,
//    which contains information about the selected slides, on the add-in's page.
let firstSlideId = 0;
function gotoSelectedSlide() {
    //Get currently selected slide's id
    Office.context.document.getSelectedDataAsync(Office.CoercionType.SlideRange, function (asyncResult) {
        if (asyncResult.status == "failed") {
            app.showNotification("Action failed with error: " + asyncResult.error.message);
        }
        else {
            firstSlideId = asyncResult.value.slides[0].id;
            app.showNotification(JSON.stringify(asyncResult.value));
        }
    });
    //Go to slide by id.
    Office.context.document.goToByIdAsync(firstSlideId, Office.GoToType.Slide, function (asyncResult) {
        if (asyncResult.status == "failed") {
            app.showNotification("Action failed with error: " + asyncResult.error.message);
        }
        else {
            app.showNotification("Navigation successful");
        }
    });
}

// Go to slide by index (PowerPoint)
// The following example shows how to:
// 1. Specify the index of the first, last, previous, or next slide to go to.
// 2. Pass an anonymous callback function that returns the status of the operation
//    to the callback parameter of the goToByIdAsync method.
// 3. Display the value on the add-in's page.
function goToSlideByIndex() {
    const goToFirst = Office.Index.First;
    const goToLast = Office.Index.Last;
    const goToPrevious = Office.Index.Previous;
    const goToNext = Office.Index.Next;

    Office.context.document.goToByIdAsync(goToNext, Office.GoToType.Index, function (asyncResult) {
        if (asyncResult.status == "failed") {
            showMessage("Action failed with error: " + asyncResult.error.message);
        }
        else {
            showMessage("Navigation successful");
        }
    });
}

removeHandlerAsync(eventType, options, callback)

Removes an event handler for the specified event type.

removeHandlerAsync(eventType: Office.EventType, options?: RemoveHandlerOptions, callback?: (result: AsyncResult<void>) => void): void;

Parameters

eventType
Office.EventType

The event type. For document can be 'Document.SelectionChanged' or 'Document.ActiveViewChanged'.

options
Office.RemoveHandlerOptions

Provides options to determine which event handler or handlers are removed.

callback

(result: Office.AsyncResult<void>) => void

Optional. A function that is invoked when the callback returns, whose only parameter is of type Office.AsyncResult.

Returns

void

Remarks

Requirement set: DocumentEvents

removeHandlerAsync(eventType, callback)

Removes an event handler for the specified event type.

removeHandlerAsync(eventType: Office.EventType, callback?: (result: AsyncResult<void>) => void): void;

Parameters

eventType
Office.EventType

The event type. For document can be 'Document.SelectionChanged' or 'Document.ActiveViewChanged'.

callback

(result: Office.AsyncResult<void>) => void

Optional. A function that is invoked when the callback returns, whose only parameter is of type Office.AsyncResult.

Returns

void

Remarks

Requirement set: DocumentEvents

Examples

// The following example removes the event handler named 'MyHandler'.
function removeSelectionChangedEventHandler() {
    Office.context.document.removeHandlerAsync(Office.EventType.DocumentSelectionChanged, {handler:MyHandler});
}

function MyHandler(eventArgs) {
    doSomethingWithDocument(eventArgs.document);
}
// The following code example uses addHandlerAsync to add an event handler for the
// ResourceSelectionChanged event and removeHandlerAsync to remove the handler.
// When a resource is selected in a resource view, the handler displays the
// resource GUID. When the handler is removed, the GUID is not displayed.
// The example assumes that your add-in has a reference to the jQuery library and
// that the following page control is defined in the content div in the page body:
// <input id="remove-handler" type="button" value="Remove handler" /><br />
// <span id="message"></span>

(function () {
    "use strict";

    // The initialize function must be run each time a new page is loaded.
    Office.initialize = function (reason) {
        $(document).ready(function () {

            // After the DOM is loaded, add-in-specific code can run.
            Office.context.document.addHandlerAsync(
                Office.EventType.ResourceSelectionChanged,
                getResourceGuid);
            $('#remove-handler').on("click", removeEventHandler);
        });
    };

    // Remove the event handler.
    function removeEventHandler() {
        Office.context.document.removeHandlerAsync(
            Office.EventType.ResourceSelectionChanged,
            {handler:getResourceGuid,
            asyncContext:'The handler is removed.'},
            function (result) {
                if (result.status === Office.AsyncResultStatus.Failed) {
                    onError(result.error);
                }
                else {
                    $('#remove-handler').attr('disabled', 'disabled');
                    $('#message').html(result.asyncContext);
                }
            }
        );
    }

    // Get the GUID of the currently selected resource and display it in the add-in.
    function getResourceGuid() {
        Office.context.document.getSelectedResourceAsync(
            function (result) {
                if (result.status === Office.AsyncResultStatus.Failed) {
                    onError(result.error);
                }
                else {
                    $('#message').html('Resource GUID: ' + result.value);
                }
            }
        );
    }

    function onError(error) {
        $('#message').html(error.name + ' ' + error.code + ': ' + error.message);
    }
})();

setResourceFieldAsync(resourceId, fieldId, fieldValue, options, callback)

Project documents only. Set resource field for specified resource ID.

Important: This API works only in Project on Windows desktop.

setResourceFieldAsync(resourceId: string, fieldId: number, fieldValue: string | number | boolean | object, options?: Office.AsyncContextOptions, callback?: (result: AsyncResult<void>) => void): void;

Parameters

resourceId

string

Either a string or value of the Resource ID.

fieldId

number

Resource Fields.

fieldValue

string | number | boolean | object

Value of the target field.

options
Office.AsyncContextOptions

Provides an option for preserving context data of any type, unchanged, for use in a callback.

callback

(result: Office.AsyncResult<void>) => void

Optional. A function that is invoked when the callback returns, whose only parameter is of type Office.AsyncResult.

Returns

void

setResourceFieldAsync(resourceId, fieldId, fieldValue, callback)

Project documents only. Set resource field for specified resource ID.

Important: This API works only in Project on Windows desktop.

setResourceFieldAsync(resourceId: string, fieldId: number, fieldValue: string | number | boolean | object, callback?: (result: AsyncResult<void>) => void): void;

Parameters

resourceId

string

Either a string or value of the Resource ID.

fieldId

number

Resource Fields.

fieldValue

string | number | boolean | object

Value of the target field.

callback

(result: Office.AsyncResult<void>) => void

Optional. A function that is invoked when the callback returns, whose only parameter is of type Office.AsyncResult.

Returns

void

Examples

// The following code example calls getSelectedResourceAsync to get the GUID of the resource that's
// currently selected in a resource view. Then it sets two resource field values by calling
// setResourceFieldAsync recursively.
// The getSelectedTaskAsync method used in the example requires that a task view
// (for example, Task Usage) is the active view and that a task is selected. See the addHandlerAsync
// method for an example that activates a button based on the active view type.
// The example assumes your add-in has a reference to the jQuery library and that the
// following page controls are defined in the content div in the page body:
// <input id="set-info" type="button" value="Set info" /><br />
// <span id="message"></span>

(function () {
    "use strict";

    // The initialize function must be run each time a new page is loaded.
    Office.initialize = function (reason) {
        $(document).ready(function () {

            // After the DOM is loaded, add-in-specific code can run.
            app.initialize();
            $('#set-info').on("click", setResourceInfo);
        });
    };

    // Get the GUID of the resource, and then get the resource fields.
    function setResourceInfo() {
        getResourceGuid().then(
            function (data) {
                setResourceFields(data);
            }
        );
    }

    // Get the GUID of the selected resource.
    function getResourceGuid() {
        const defer = $.Deferred();
        Office.context.document.getSelectedResourceAsync(
            function (result) {
                if (result.status === Office.AsyncResultStatus.Failed) {
                    onError(result.error);
                }
                else {
                    defer.resolve(result.value);
                }
            }
        );
        return defer.promise();
    }

    // Set the specified fields for the selected resource.
    function setResourceFields(resourceGuid) {
        const targetFields = [Office.ProjectResourceFields.StandardRate, Office.ProjectResourceFields.Notes];
        const fieldValues = [.28, 'Notes for the resource.'];

        // Set the field value. If the call is successful, set the next field.
        for (let i = 0; i < targetFields.length; i++) {
            Office.context.document.setResourceFieldAsync(
                resourceGuid,
                targetFields[i],
                fieldValues[i],
                function (result) {
                    if (result.status === Office.AsyncResultStatus.Succeeded) {
                        i++;
                    }
                    else {
                        onError(result.error);
                    }
                }
            );
        }
        $('#message').html('Field values set');
    }

    function onError(error) {
        app.showNotification(error.name + ' ' + error.code + ': ' + error.message);
    }
})();

setSelectedDataAsync(data, options, callback)

Writes the specified data into the current selection.

setSelectedDataAsync(data: string | TableData | any[][], options?: SetSelectedDataOptions, callback?: (result: AsyncResult<void>) => void): void;

Parameters

data

string | Office.TableData | any[][]

The data to be set. Either a string or Office.CoercionType value, 2D array or TableData object.

If the value passed for data is:

  • A string: Plain text or anything that can be coerced to a string will be inserted. In Excel, you can also specify data as a valid formula to add that formula to the selected cell. For example, setting data to "=SUM(A1:A5)" will total the values in the specified range. However, when you set a formula on the bound cell, after doing so, you can't read the added formula (or any pre-existing formula) from the bound cell. If you call the Document.getSelectedDataAsync method on the selected cell to read its data, the method can return only the data displayed in the cell (the formula's result).

  • An array of arrays ("matrix"): Tabular data without headers will be inserted. For example, to write data to three rows in two columns, you can pass an array like this: [["R1C1", "R1C2"], ["R2C1", "R2C2"], ["R3C1", "R3C2"]]. To write a single column of three rows, pass an array like this: [["R1C1"], ["R2C1"], ["R3C1"]]

In Excel, you can also specify data as an array of arrays that contains valid formulas to add them to the selected cells. For example if no other data will be overwritten, setting data to [["=SUM(A1:A5)","=AVERAGE(A1:A5)"]] will add those two formulas to the selection. Just as when setting a formula on a single cell as "text", you can't read the added formulas (or any pre-existing formulas) after they have been set - you can only read the formulas' results.

  • A TableData object: A table with headers will be inserted. In Excel, if you specify formulas in the TableData object you pass for the data parameter, you might not get the results you expect due to the "calculated columns" feature of Excel, which automatically duplicates formulas within a column. To work around this when you want to write data that contains formulas to a selected table, try specifying the data as an array of arrays (instead of a TableData object), and specify the coercionType as Microsoft.Office.Matrix or "matrix". However, this technique will block the "calculated columns" feature only when one of the following conditions is met: (1) you are writing to all the cells of the column, or (2) there are already at least two different formulas in the column.
options
Office.SetSelectedDataOptions

Provides options for how to insert data to the selection.

callback

(result: Office.AsyncResult<void>) => void

Optional. A function that is invoked when the callback returns, whose only parameter is of type Office.AsyncResult. The AsyncResult.value property always returns undefined because there is no object or data to retrieve.

Returns

void

Remarks

Requirement sets:

Application-specific behaviors

The following application-specific actions apply when writing data to a selection.

Application Condition Behavior
Word If there's no selection and the insertion point is at a valid location, the specified data is inserted at the insertion point If data is a string, the specified text is inserted.
If data is an array of arrays ("matrix") or a TableData object, a new Word table is inserted.
If data is HTML, the specified HTML is inserted. (**Important**: If any of the HTML you insert is invalid, Word won't raise an error. Word will insert as much of the HTML as it can and omits any invalid data).
If data is Office Open XML, the specified XML is inserted.
If data is a Base64-encoded image stream, the specified image is inserted.
If there's a selection It will be replaced with the specified data following the same rules as above.
Insert images Inserted images are placed inline. The imageLeft and imageTop parameters are ignored. The image aspect ratio is always locked. If only one of the imageWidth and imageHeight parameter is given, the other value will be automatically scaled to keep the original aspect ratio.
Excel If a single cell is selected If data is a string, the specified text is inserted as the value of the current cell.
If data is an array of arrays ("matrix"), the specified set of rows and columns are inserted, if no other data in surrounding cells will be overwritten.
If data is a TableData object, a new Excel table with the specified set of rows and headers is inserted, if no other data in surrounding cells will be overwritten.
If multiple cells are selected If the shape doesn't match the shape of data, an error is returned.
If the shape of the selection exactly matches the shape of data, the values of the selected cells are updated based on the values in data.
Insert images Inserted images are floating. The position imageLeft and imageTop parameters are relative to currently selected cells. Negative imageLeft and imageTop values are allowed and possibly readjusted by Excel to position the image inside a worksheet. Image aspect ratio is locked unless both imageWidth and imageHeight parameters are provided. If only one of the imageWidth and imageHeight parameter is given, the other value will be automatically scaled to keep the original aspect ratio.
All other cases An error is returned.
Excel on the web In addition to the behaviors described for Excel above, these limits apply when writing data in Excel on the web The total number of cells you can write to a worksheet with the data parameter can't exceed 20,000 in a single call to this method.
The number of formatting groups passed to the cellFormat parameter can't exceed 100. A single formatting group consists of a set of formatting applied to a specified range of cells.
PowerPoint Insert image Inserted images are floating. The position imageLeft and imageTop parameters are optional but if provided, both should be present. If a single value is provided, it will be ignored. Negative imageLeft and imageTop values are allowed and can position an image outside of a slide. If no optional parameter is given and slide has a placeholder, the image will replace the placeholder in the slide. Image aspect ratio will be locked unless both imageWidth and imageHeight parameters are provided. If only one of the imageWidth and imageHeight parameter is given, the other value will be automatically scaled to keep the original aspect ratio.

Applications

The possible values for the Office.CoercionType parameter vary by the Office application.

CoercionType Supported applications
Office.CoercionType.Html
  • Word
Office.CoercionType.Matrix (array of arrays)
  • Excel
  • Word
Office.CoercionType.Ooxml (Office Open XML)
  • Word
Office.CoercionType.SlideRange
  • PowerPoint on the web and on Windows
Office.CoercionType.Table (TableData object)
  • Excel
  • Word
Office.CoercionType.Text (string)
  • Excel
  • PowerPoint
  • Project
  • Word
Office.CoercionType.XmlSvg
  • Excel on Windows and on Mac
  • PowerPoint on the web, on Windows, and on Mac
  • Word on Windows and on Mac

Examples

// The following example sets the selected text or cell to "Hello World!", 
// and if that fails, displays the value of the error.message property.
function writeText() {
    Office.context.document.setSelectedDataAsync("Hello World!",
        function (asyncResult) {
            const error = asyncResult.error;
            if (asyncResult.status === Office.AsyncResultStatus.Failed){
                write(error.name + ": " + error.message);
            }
        });
}

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

// Specifying the optional coercionType parameter lets you specify the kind of data you want to write
// to a selection. The following example writes data as an array of three rows of two columns, 
// specifying the coercionType as `Matrix` for that data structure, and if that fails, 
// displays the value of the error.message property.
function writeMatrix() {
    Office.context.document.setSelectedDataAsync(
        [["Red", "Rojo"], ["Green", "Verde"], ["Blue", "Azul"]],
        {coercionType: Office.CoercionType.Matrix}
        function (asyncResult) {
            const error = asyncResult.error;
            if (asyncResult.status === Office.AsyncResultStatus.Failed){
                write(error.name + ": " + error.message);
            }
        });
}

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

// The following example writes data as a one column table with a header and four rows, 
// specifying the coercionType as `Table` for that data structure, and if that fails, 
// displays the value of the error.message property.
function writeTable() {
    // Build table.
    const myTable = new Office.TableData();
    myTable.headers = [["Cities"]];
    myTable.rows = [['Berlin'], ['Roma'], ['Tokyo'], ['Seattle']];

    // Write table.
    Office.context.document.setSelectedDataAsync(myTable, {coercionType: Office.CoercionType.Table},
        function (result) {
            const error = result.error
            if (result.status === Office.AsyncResultStatus.Failed) {
                write(error.name + ": " + error.message);
            }
    });
}

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

// In Word if you want to write HTML to the selection, you can specify the coercionType parameter as `Html`
// as shown in the following example, which uses HTML <b> tags to make "Hello" bold.
function writeHtmlData() {
    Office.context.document.setSelectedDataAsync(
        "<b>Hello</b> World!", {coercionType: Office.CoercionType.Html}, function (asyncResult) {
            if (asyncResult.status === Office.AsyncResultStatus.Failed) {
                write('Error: ' + asyncResult.error.message);
            }
    });
}

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

// In Word, PowerPoint, or Excel, if you want to write an image to the selection, you can specify the coercionType
// parameter as `Image` as shown in the following example. Note that imageLeft and imageTop are ignored by Word.
function insertPictureAtSelection(base64EncodedImageStr) {

    Office.context.document.setSelectedDataAsync(base64EncodedImageStr, {
        coercionType: Office.CoercionType.Image,
        imageLeft: 50,
        imageTop: 50,
        imageWidth: 100,
        imageHeight: 100
    },
    function (asyncResult) {
        if (asyncResult.status === Office.AsyncResultStatus.Failed) {
            console.log("Action failed with error: " + asyncResult.error.message);
        }
    });
}

// In Word, PowerPoint, or Excel, if you want to write an scalable vector graphic (SVG) to the selection, you can specify the 
// coercionType parameter as `XmlSvg` as shown in the following example. Note that imageLeft and imageTop are ignored by Word.
function insertSvgAtSelection(base64EncodedImageStr) {
    Office.context.document.setSelectedDataAsync(getImageAsBase64String(), {
        coercionType: Office.CoercionType.XmlSvg,
        imageLeft: 50,
        imageTop: 50,
        imageWidth: 400
    },
        function (asyncResult) {
            if (asyncResult.status === Office.AsyncResultStatus.Failed) {
                console.log(asyncResult.error.message);
            }
        });
}

setSelectedDataAsync(data, callback)

Writes the specified data into the current selection.

setSelectedDataAsync(data: string | TableData | any[][], callback?: (result: AsyncResult<void>) => void): void;

Parameters

data

string | Office.TableData | any[][]

The data to be set. Either a string or Office.CoercionType value, 2D array or TableData object.

If the value passed for data is:

  • A string: Plain text or anything that can be coerced to a string will be inserted. In Excel, you can also specify data as a valid formula to add that formula to the selected cell. For example, setting data to "=SUM(A1:A5)" will total the values in the specified range. However, when you set a formula on the bound cell, after doing so, you can't read the added formula (or any pre-existing formula) from the bound cell. If you call the Document.getSelectedDataAsync method on the selected cell to read its data, the method can return only the data displayed in the cell (the formula's result).

  • An array of arrays ("matrix"): Tabular data without headers will be inserted. For example, to write data to three rows in two columns, you can pass an array like this: [["R1C1", "R1C2"], ["R2C1", "R2C2"], ["R3C1", "R3C2"]]. To write a single column of three rows, pass an array like this: [["R1C1"], ["R2C1"], ["R3C1"]]

In Excel, you can also specify data as an array of arrays that contains valid formulas to add them to the selected cells. For example if no other data will be overwritten, setting data to [["=SUM(A1:A5)","=AVERAGE(A1:A5)"]] will add those two formulas to the selection. Just as when setting a formula on a single cell as "text", you can't read the added formulas (or any pre-existing formulas) after they have been set - you can only read the formulas' results.

  • A TableData object: A table with headers will be inserted. In Excel, if you specify formulas in the TableData object you pass for the data parameter, you might not get the results you expect due to the "calculated columns" feature of Excel, which automatically duplicates formulas within a column. To work around this when you want to write data that contains formulas to a selected table, try specifying the data as an array of arrays (instead of a TableData object), and specify the coercionType as Microsoft.Office.Matrix or "matrix". However, this technique will block the "calculated columns" feature only when one of the following conditions is met: (1) you are writing to all the cells of the column, or (2) there are already at least two different formulas in the column.
callback

(result: Office.AsyncResult<void>) => void

Optional. A function that is invoked when the callback returns, whose only parameter is of type Office.AsyncResult. The AsyncResult.value property always returns undefined because there is no object or data to retrieve.

Returns

void

Remarks

Requirement sets:

Application-specific behaviors

The following application-specific actions apply when writing data to a selection.

Application Condition Behavior
Word If there's no selection and the insertion point is at a valid location, the specified `data` is inserted at the insertion point If data is a string, the specified text is inserted.
If data is an array of arrays ("matrix") or a TableData object, a new Word table is inserted.
If data is HTML, the specified HTML is inserted. (**Important**: If any of the HTML you insert is invalid, Word won't raise an error. Word will insert as much of the HTML as it can and omits any invalid data).
If data is Office Open XML, the specified XML is inserted.
If data is a Base64-encoded image stream, the specified image is inserted.
If there's a selection It will be replaced with the specified data following the same rules as above.
Insert images Inserted images are placed inline. The imageLeft and imageTop parameters are ignored. The image aspect ratio is always locked. If only one of the imageWidth and imageHeight parameter is given, the other value will be automatically scaled to keep the original aspect ratio.
Excel If a single cell is selected If data is a string, the specified text is inserted as the value of the current cell.
If data is an array of arrays ("matrix"), the specified set of rows and columns are inserted, if no other data in surrounding cells will be overwritten.
If data is a TableData object, a new Excel table with the specified set of rows and headers is inserted, if no other data in surrounding cells will be overwritten.
If multiple cells are selected If the shape doesn't match the shape of data, an error is returned.
If the shape of the selection exactly matches the shape of data, the values of the selected cells are updated based on the values in data.
Insert images Inserted images are floating. The position imageLeft and imageTop parameters are relative to currently selected cells. Negative imageLeft and imageTop values are allowed and possibly readjusted by Excel to position the image inside a worksheet. Image aspect ratio is locked unless both imageWidth and imageHeight parameters are provided. If only one of the imageWidth and imageHeight parameter is given, the other value will be automatically scaled to keep the original aspect ratio.
All other cases An error is returned.
Excel on the web In addition to the behaviors described for Excel above, these limits apply when writing data in Excel on the web The total number of cells you can write to a worksheet with the data parameter can't exceed 20,000 in a single call to this method.
The number of formatting groups passed to the cellFormat parameter can't exceed 100. A single formatting group consists of a set of formatting applied to a specified range of cells.
PowerPoint Insert image Inserted images are floating. The position imageLeft and imageTop parameters are optional but if provided, both should be present. If a single value is provided, it will be ignored. Negative imageLeft and imageTop values are allowed and can position an image outside of a slide. If no optional parameter is given and slide has a placeholder, the image will replace the placeholder in the slide. Image aspect ratio will be locked unless both imageWidth and imageHeight parameters are provided. If only one of the imageWidth and imageHeight parameter is given, the other value will be automatically scaled to keep the original aspect ratio.

Applications

The possible values for the Office.CoercionType parameter vary by the Office application.

CoercionType Supported applications
Office.CoercionType.Html
  • Word
Office.CoercionType.Matrix (array of arrays)
  • Excel
  • Word
Office.CoercionType.Ooxml (Office Open XML)
  • Word
Office.CoercionType.SlideRange
  • PowerPoint on the web and on Windows
Office.CoercionType.Table (TableData object)
  • Excel
  • Word
Office.CoercionType.Text (string)
  • Excel
  • PowerPoint
  • Project
  • Word
Office.CoercionType.XmlSvg
  • Excel on Windows and on Mac
  • PowerPoint on the web, on Windows, and on Mac
  • Word on Windows and on Mac

setTaskFieldAsync(taskId, fieldId, fieldValue, options, callback)

Project documents only. Set task field for specified task ID.

Important: This API works only in Project on Windows desktop.

setTaskFieldAsync(taskId: string, fieldId: number, fieldValue: string | number | boolean | object, options?: Office.AsyncContextOptions, callback?: (result: AsyncResult<void>) => void): void;

Parameters

taskId

string

Either a string or value of the task ID.

fieldId

number

Task Fields.

fieldValue

string | number | boolean | object

Value of the target field.

options
Office.AsyncContextOptions

Provides an option for preserving context data of any type, unchanged, for use in a callback.

callback

(result: Office.AsyncResult<void>) => void

Optional. A function that is invoked when the callback returns, whose only parameter is of type Office.AsyncResult.

Returns

void

setTaskFieldAsync(taskId, fieldId, fieldValue, callback)

Project documents only. Set task field for specified task ID.

Important: This API works only in Project on Windows desktop.

setTaskFieldAsync(taskId: string, fieldId: number, fieldValue: string | number | boolean | object, callback?: (result: AsyncResult<void>) => void): void;

Parameters

taskId

string

Either a string or value of the Task ID.

fieldId

number

Task Fields.

fieldValue

string | number | boolean | object

Value of the target field.

callback

(result: Office.AsyncResult<void>) => void

Optional. A function that is invoked when the callback returns, whose only parameter is of type Office.AsyncResult.

Returns

void

Examples

// The following code example calls getSelectedTaskAsync to get the GUID of the task that's
// currently selected in a task view. Then it sets two task field values by calling
// setTaskFieldAsync recursively.
// The getSelectedTaskAsync method used in the example requires that a task view
// (for example, Task Usage) is the active view and that a task is selected. See the
// addHandlerAsync method for an example that activates a button based on the active view type.
// The example assumes your add-in has a reference to the jQuery library and that the
// following page controls are defined in the content div in the page body:
// <input id="set-info" type="button" value="Set info" /><br />
// <span id="message"></span>

(function () {
    "use strict";

    // The initialize function must be run each time a new page is loaded.
    Office.initialize = function (reason) {
        $(document).ready(function () {
            
            // After the DOM is loaded, add-in-specific code can run.
            app.initialize();
            $('#set-info').on("click", setTaskInfo);
        });
    };

    // Get the GUID of the task, and then get the task fields.
    function setTaskInfo() {
        getTaskGuid().then(
            function (data) {
                setTaskFields(data);
            }
        );
    }

    // Get the GUID of the selected task.
    function getTaskGuid() {
        const defer = $.Deferred();
        Office.context.document.getSelectedTaskAsync(
            function (result) {
                if (result.status === Office.AsyncResultStatus.Failed) {
                    onError(result.error);
                }
                else {
                    defer.resolve(result.value);
                }
            }
        );
        return defer.promise();
    }

    // Set the specified fields for the selected task.
    function setTaskFields(taskGuid) {
        const targetFields = [Office.ProjectTaskFields.Active, Office.ProjectTaskFields.Notes];
        const fieldValues = [true, 'Notes for the task.'];

        // Set the field value. If the call is successful, set the next field.
        for (let i = 0; i < targetFields.length; i++) {
            Office.context.document.setTaskFieldAsync(
                taskGuid,
                targetFields[i],
                fieldValues[i],
                function (result) {
                    if (result.status === Office.AsyncResultStatus.Succeeded) {
                        i++;
                    }
                    else {
                        onError(result.error);
                    }
                }
            );
        }
        $('#message').html('Field values set');
    }

    function onError(error) {
        app.showNotification(error.name + ' ' + error.code + ': ' + error.message);
    }
})();