Office.Context interface 
表示外接程序的运行时环境,并提供对 API 的关键对象的访问。 当前上下文作为 Office 的属性存在。 它使用 Office.context进行访问。
注解
支持详细信息
有关 Office 应用程序和服务器要求的详细信息,请参阅 运行 Office 外接程序的要求。
支持的应用程序(按平台)
| Office 网页版 | Windows 版 Office | Mac 版 Office | iPad 版 Office | 移动设备上的 Outlook | |
|---|---|---|---|---|---|
| 胜过 | 支持 | 支持 | 支持 | 支持 | 不适用 | 
| 展望 | 支持 | 支持 | 支持 | 支持 | 支持 | 
| PowerPoint | 支持 | 支持 | 支持 | 支持 | 不适用 | 
| 项目 | 不支持 | 支持 | 支持 | 不支持 | 不适用 | 
| Word | 支持 | 支持 | 支持 | 支持 | 不适用 | 
示例
// Get the Office host, version, and platform in which the add-in is running.
const contextInfo = Office.context.diagnostics;
console.log("Office application: " + contextInfo.host);
console.log("Office version: " + contextInfo.version);
console.log("Platform: " + contextInfo.platform);
属性
| commerce | 如果当前平台允许加载项显示用于销售或升级的 UI,则为 True;否则返回 False。 | 
| content | 获取用户指定的区域设置(语言)以编辑文档或项目。 | 
| diagnostics | 获取有关运行加载项的环境的信息。 | 
| display | 获取用户为 Office 应用程序的 UI 指定的区域设置 (语言) 。 | 
| document | 获取表示正与内容或任务窗格外接程序交互的文档的对象。 | 
| host | 包含运行加载项的 Office 应用程序。 | 
| license | 获取用户的 Office 安装的许可证信息。 | 
| mailbox | 提供对Microsoft Outlook 外接程序对象模型的访问权限。 | 
| office | 提供了访问 Office 主题颜色的属性。 | 
| partition | 获取本地存储的分区键。 加载项应将此分区键用作存储键的一部分,以安全地存储数据。 分区键位于  | 
| platform | 提供运行加载项的平台。 | 
| requirements | 提供一种方法,用于确定当前 Office 应用程序和平台支持哪些要求集。 | 
| roaming | 获取一个对象,它表示保存到用户邮箱的邮件外接程序的自定义设置或状态。 通过  | 
| sensitivity | 获取要检查 Outlook 中敏感度标签目录的状态的 对象,并在启用目录时检索所有可用的敏感度标签。 | 
| touch | 指定平台和设备是否允许触摸交互。 如果加载项在触摸设备(如 iPad)上运行,则为 True;否则为 false。 | 
| ui | 提供可用于创建和操作 UI 组件(如对话框)的对象和方法。 | 
| urls | 获取用于检索外接程序的运行时 URL 的 对象。 | 
属性详细信息
		commerceAllowed
	 
	如果当前平台允许加载项显示用于销售或升级的 UI,则为 True;否则返回 False。
commerceAllowed: boolean;属性值
boolean
注解
应用程序:Excel、Word
              commerceAllowed 仅在 iPad 上的 Office 中受支持。
iOS 应用商店不支持提供其他付款系统的链接的应用程序和外接程序。 但是,在 Windows 桌面或浏览器中的 Office 中运行的 Office 加载项允许此类链接。 如果希望外接程序的 UI 在 iOS 以外的平台上提供指向外部支付系统的链接,可以使用 commerceAllowed 属性来控制显示该链接的日期。
示例
// Check if the add-in is running on an iPad.
const allowCommerce = Office.context.commerceAllowed;
const isTouchEnabled = Office.context.touchEnabled;
if (!allowCommerce && isTouchEnabled) {
    // Add-in is running on an iPad.
    // Do something.
}
		contentLanguage
	 
	获取用户指定的区域设置(语言)以编辑文档或项目。
contentLanguage: string;属性值
string
注解
该值contentLanguage反映 Office 应用程序中使用“文件>选项语言”>指定的“编辑语言”设置。
支持详细信息
有关 Office 应用程序和服务器要求的详细信息,请参阅 运行 Office 外接程序的要求。
支持的应用程序(按平台)
| Office 网页版 | Windows 版 Office | Mac 版 Office | iPad 版 Office | 移动设备上的 Outlook | |
|---|---|---|---|---|---|
| 胜过 | 支持 | 支持 | 不支持 | 支持 | 不适用 | 
| 展望 | 支持 | 支持 | 支持 | 支持 | 支持 | 
| PowerPoint | 支持 | 支持 | 不支持 | 支持 | 不适用 | 
| 项目 | 不支持 | 支持 | 不支持 | 不支持 | 不适用 | 
| Word | 支持 | 支持 | 不支持 | 支持 | 不适用 | 
示例
function sayHelloWithContentLanguage() {
    const myContentLanguage = Office.context.contentLanguage;
    switch (myContentLanguage) {
        case 'en-US':
            write('Hello!');
            break;
        case 'en-NZ':
            write('G\'day mate!');
            break;
    }
}
// Function that writes to a div with id='message' on the page.
function write(message){
    document.getElementById('message').innerText += message; 
}
diagnostics
获取有关运行加载项的环境的信息。
diagnostics: ContextInformation;属性值
注解
重要提示:在 Outlook 中,此属性从邮箱要求集 1.5 开始可用。 对于所有邮箱要求集,可以使用 Office.context.mailbox.诊断 属性获取类似信息。
示例
const contextInfo = Office.context.diagnostics;
console.log("Office application: " + contextInfo.host);
console.log("Office version: " + contextInfo.version);
console.log("Platform: " + contextInfo.platform);
		displayLanguage
	 
	获取用户为 Office 应用程序的 UI 指定的区域设置 (语言) 。
displayLanguage: string;属性值
string
注解
返回的值是 RFC 1766 Language 标记格式的字符串,例如 en-US。
该值displayLanguage反映 Office 应用程序中使用“文件选项语言”>>指定的当前“显示语言”设置。
在 Outlook 中使用时,适用的模式为Compose或读取。
支持详细信息
有关 Office 应用程序和服务器要求的详细信息,请参阅 运行 Office 外接程序的要求。
支持的应用程序(按平台)
| Office 网页版 | Windows 版 Office | Mac 版 Office | iPad 版 Office | 移动设备上的 Outlook | |
|---|---|---|---|---|---|
| 胜过 | 支持 | 支持 | 支持 | 支持 | 不适用 | 
| 展望 | 支持 | 支持 | 支持 | 支持 | 支持 | 
| PowerPoint | 支持 | 支持 | 支持 | 支持 | 不适用 | 
| 项目 | 不支持 | 支持 | 支持 | 不支持 | 不适用 | 
| Word | 不支持 | 支持 | 支持 | 支持 | 不适用 | 
示例
function sayHelloWithDisplayLanguage() {
    const myDisplayLanguage = Office.context.displayLanguage;
    switch (myDisplayLanguage) {
        case 'en-US':
            write('Hello!');
            break;
        case 'en-NZ':
            write('G\'day mate!');
            break;
    }
}
// Function that writes to a div with id='message' on the page.
function write(message){
    document.getElementById('message').innerText += message; 
}
document
获取表示正与内容或任务窗格外接程序交互的文档的对象。
document: Office.Document;属性值
示例
// Extension initialization code.
let _document;
// The initialize function is required for all add-ins.
Office.initialize = function () {
    // Checks for the DOM to load using the jQuery ready method.
    $(document).ready(function () {
    // After the DOM is loaded, code specific to the add-in can run.
    // Initialize instance variables to access API objects.
    _document = Office.context.document;
    });
}
host
包含运行加载项的 Office 应用程序。
host: HostType;属性值
注解
              重要提示:在 Outlook 中,此属性从邮箱要求集 1.5 开始可用。 还可以使用 Office.context.diagnostics 属性获取从要求集 1.5 开始的应用程序。 对于所有邮箱要求集,可以使用 Office.context.mailbox.诊断 属性获取类似信息。
示例
const host = Office.context.host;
if (host === Office.HostType.Excel || host === Office.HostType.PowerPoint || host === Office.HostType.Word) {
    // Do something.
} else if (host === Office.HostType.Outlook) {
    // Do something.
}
license
获取用户的 Office 安装的许可证信息。
license: object;属性值
object
示例
const license = Office.context.license;
console.log(`Office license: ${license}`);
mailbox
提供对Microsoft Outlook 外接程序对象模型的访问权限。
mailbox: Office.Mailbox;属性值
注解
最低权限级别: 受限
适用的 Outlook 模式:Compose或读取
键属性:
- diagnostics:向 Outlook 加载项提供诊断信息。
- item:提供用于在 Outlook 外接程序中访问邮件或约会的方法和属性。
- userProfile:提供有关 Outlook 外接程序中用户的信息。
示例
// The following line of code access the item object of the JavaScript API for Office.
const item = Office.context.mailbox.item;
		officeTheme
	 
	提供了访问 Office 主题颜色的属性。
officeTheme: OfficeTheme;属性值
示例
function applyOfficeTheme() {
    // Identify the current Office theme in use.
    const currentOfficeTheme = Office.context.officeTheme.themeId;
    if (currentOfficeTheme === Office.ThemeId.Colorful || currentOfficeTheme === Office.ThemeId.White) {
        console.log("No changes required.");
    }
    // Get the colors of the current Office theme.
    const bodyBackgroundColor = Office.context.officeTheme.bodyBackgroundColor;
    const bodyForegroundColor = Office.context.officeTheme.bodyForegroundColor;
    const controlBackgroundColor = Office.context.officeTheme.controlBackgroundColor;
    const controlForegroundColor = Office.context.officeTheme.controlForegroundColor;
    // Apply theme colors to a CSS class.
    $("body").css("background-color", bodyBackgroundColor);
    if (Office.context.officeTheme.isDarkTheme()) {
        $("h1").css("color", controlForegroundColor);
    }
}
		partitionKey
	 
	获取本地存储的分区键。 加载项应将此分区键用作存储键的一部分,以安全地存储数据。 分区键位于 undefined 没有分区的环境中,例如 Windows 应用程序的浏览器控件。
partitionKey: string;属性值
string
注解
有关详细信息,请参阅 保留加载项状态和设置 一文。
示例
// Store the value "Hello" in local storage with the key "myKey1".
setInLocalStorage("myKey1", "Hello");
// ... 
// Retrieve the value stored in local storage under the key "myKey1".
const message = getFromLocalStorage("myKey1");
console.log(message);
// ...
function setInLocalStorage(key: string, value: string) {
    const myPartitionKey = Office.context.partitionKey;
    // Check if local storage is partitioned. 
    // If so, use the partition to ensure the data is only accessible by your add-in.
    if (myPartitionKey) {
        localStorage.setItem(myPartitionKey + key, value);
    } else {
        localStorage.setItem(key, value);
    }
}
function getFromLocalStorage(key: string) {
    const myPartitionKey = Office.context.partitionKey;
    // Check if local storage is partitioned.
    if (myPartitionKey) {
        return localStorage.getItem(myPartitionKey + key);
    } else {
        return localStorage.getItem(key);
    }
}
platform
提供运行加载项的平台。
platform: PlatformType;属性值
注解
重要说明:
- 在 Outlook 中,此属性从邮箱要求集 1.5 开始可用。 还可以使用 - Office.context.diagnostics属性从要求集 1.5 开始获取平台。 对于所有邮箱要求集,可以使用 Office.context.mailbox.诊断 属性获取类似信息。
- 在 Outlook 中, - OfficeOnline如果加载项在 Outlook 网页版 或 Windows 上的新 Outlook 中运行,则返回 。
示例
// Request permission from a user to access their devices from Office on the web.
if (Office.context.platform === Office.PlatformType.OfficeOnline) {
    const deviceCapabilities = [
        Office.DevicePermissionType.camera,
        Office.DevicePermissionType.microphone
    ];
    Office.devicePermission
        .requestPermissions(deviceCapabilities)
        .then((isGranted) => {
            if (isGranted) {
                // Do something with device capabilities.
            }
        })
        .catch((error) => {
            console.log("Permission denied.");
            console.error(error);
        });
}
requirements
提供一种方法,用于确定当前 Office 应用程序和平台支持哪些要求集。
requirements: RequirementSetSupport;属性值
示例
// To use the setCellProperties API, check if ExcelApi 1.9 is supported.
if (Office.context.requirements.isSetSupported("ExcelApi", "1.9")) {
    const cellProperties: Excel.SettableCellProperties[][] =
    colors2D.map(row =>
        row.map(color =>
            ({
                format: {
                    fill: {
                        color: color
                    }
                }
            })
        )
    );
    sheet.getRangeByIndexes(1, 1, originalSize, originalSize).setCellProperties(cellProperties);
}
...
		roamingSettings
	 
	获取一个对象,它表示保存到用户邮箱的邮件外接程序的自定义设置或状态。
通过 RoamingSettings 对象,可以存储和访问存储在用户邮箱中的邮件加载项的数据,因此当加载项从用于访问该邮箱的任何客户端应用程序运行时,该外接程序可以使用该加载项。
roamingSettings: Office.RoamingSettings;属性值
注解
最低权限级别: 受限
适用的 Outlook 模式:Compose或读取
示例
// Get the current value of the 'myKey' setting.
const value = Office.context.roamingSettings.get('myKey');
// Update the value of the 'myKey' setting.
Office.context.roamingSettings.set('myKey', 'Hello World!');
// Persist the change.
Office.context.roamingSettings.saveAsync();
		sensitivityLabelsCatalog
	  
	获取要检查 Outlook 中敏感度标签目录的状态的 对象,并在启用目录时检索所有可用的敏感度标签。
sensitivityLabelsCatalog: Office.SensitivityLabelsCatalog;属性值
注解
最低权限级别: 读/写项
适用的 Outlook 模式:Compose
示例
// Check if the catalog of sensitivity labels is enabled on the current mailbox.
Office.context.sensitivityLabelsCatalog.getIsEnabledAsync((asyncResult) => {
    // If the catalog is enabled, get all available sensitivity labels.
    if (asyncResult.status === Office.AsyncResultStatus.Succeeded && asyncResult.value == true) {
        Office.context.sensitivityLabelsCatalog.getAsync((asyncResult) => {
            if (asyncResult.status === Office.AsyncResultStatus.Succeeded) {
                const catalog = asyncResult.value;
                console.log("Sensitivity Labels Catalog:");
                console.log(JSON.stringify(catalog));
            } else {
                console.log("Action failed with error: " + asyncResult.error.message);
            }
        });
    } else {
        console.log("Action failed with error: " + asyncResult.error.message);
    }
});
		touchEnabled
	 
	指定平台和设备是否允许触摸交互。 如果加载项在触摸设备(如 iPad)上运行,则为 True;否则为 false。
touchEnabled: boolean;属性值
boolean
注解
应用程序:Excel、PowerPoint Word
              touchEnabled 仅在 iPad 上的 Office 中受支持。
使用 touchEnabled 属性可确定加载项何时在触摸设备上运行,并在必要时调整外接程序 UI 中控件的类型以及元素的大小和间距,以适应触摸交互。
示例
// Check if the add-in is running on an iPad.
const allowCommerce = Office.context.commerceAllowed;
const isTouchEnabled = Office.context.touchEnabled;
if (!allowCommerce && isTouchEnabled) {
    // Add-in is running on an iPad.
    // Do something.
}
ui
提供可用于创建和操作 UI 组件(如对话框)的对象和方法。
ui: UI;属性值
示例
// Open a dialog and register an event handler.
Office.context.ui.displayDialogAsync(
    "https://www.contoso.com/myDialog.html",
    { height: 30, width: 20 },
    (asyncResult) => {
        const dialog = asyncResult.value;
        dialog.addEventHandler(Office.EventType.DialogMessageReceived, (arg) => {
            dialog.close();
            processMessage(arg);
        });
    }
);
urls
获取用于检索外接程序的运行时 URL 的 对象。
urls: Urls;属性值
注解
应用程序:Outlook 网页版和 Windows (新客户端和经典客户端)
最低权限级别: 受限
适用的 Outlook 模式:Compose或读取
重要说明:
- 在 Outlook 网页版 和新的 Outlook on Windows 中,实现任务窗格的加载项不支持此 API。 在这些客户端上,API 仅在实现基于事件的激活或集成垃圾邮件报告的加载项中受支持。 
- 在经典 Outlook on Windows 中,实现任务窗格、基于事件的激活或集成垃圾邮件报告的加载项支持此 API。 
示例
// Get the value of the first parameter of the JavaScript runtime URL.
// For example, if the URL is https://wwww.contoso.com/training?key1=value1&key2=value2,
// the following function logs "First parameter value: value1" to the console.
const url = Office.context.urls.javascriptRuntimeUrl;
const regex = /=([^&]+)/;
console.log(`First parameter value: ${url.match(regex)[1]}`);