如何找到 Office AddIn Host 它是一个 Word 应用程序或 Excel 使用 office.js?

How to find the Office AddIn Host it is a Word application or Excel using office.js?

我正在创建一个 office AddIn,它在 excel 和 word 应用程序中都可以工作,并且如果它是一个 word 或 excel host 我想执行不同的逻辑。我正在使用 office.js 创建办公室插件。

例如:-

let say type="Excel" // after some logic executed 

if(type=="Excel")
 {
//run code for excel applications 
}
else
{
//run code for word applications
}

我试过使用波纹管:-

 if (Office.context.requirements.isSetSupported('ExcelApi', '1.1')) {
            alert("yes it is excel");
        }

但是当我 运行 它在 excel 时它不起作用。

我也在清单文件中发送了主机

 <Hosts>
     <Host Name="Document" />
    <Host Name="Workbook" />
  </Hosts>

我也得到了一些代码改变做了很多谷歌搜索我找到了下面的代码 这对我不起作用

function getHostInfo() {
    var _requirements = Office.context.requirements;
    var types = ['Excel', 'Word'];
    var minVersions = ['1.1', '1.0']; // Start with the highest version

    // Loop through types and minVersions
    for (var type in types) {
        for (var minVersion in minVersions) {

            // Append "Api" to the type for set name, i.e. "ExcelApi" or "WordApi"
            if (_requirements.isSetSupported(types[type] + 'Api', minVersions[minVersion])) {
                return {
                    type: types[type],
                    apiVersion: minVersions[minVersion]
                }
            }
        }
    }
};

谢谢

2016 年 12 月 5 日更新:我们将很快发布一个 API 来检测主机和平台信息(部分是为了回应 _host_info URL 人们非官方依赖的参数,最近需要从 Office Online 中删除)。我们也有一个临时的解决方法,以应对即将到来的官方 API。 有关详细信息,请参阅“In Excel Online, OfficeJS API is not passing the host_Info_ parameter anymore to Excel Add-In”。

请注意,对于许多 点亮场景 ,您最好还是使用 API 设置检测。有关要求集的更多信息,请参阅“”。


如果您在 Excel 2016 年,if (Office.context.requirements.isSetSupported('ExcelApi', '1.1')) 应该适合您。它在 2013 年将不起作用(即 return false)。

如果您的目标是 Office 2013,并且只需要一个针对 Word 的解决方案 & Excel,您可以使用编写 OpenXML 的能力作为一个区分因素(Word 可以,Excel 不能).所以检查 Office.context.requirements.isSetSupported('OoxmlCoercion')。对于 Word,它将 return 为真,对于 Excel 为假。

您始终可以检查 location.search 对象 - return 应该是 ?_host_Info=Word|Win32|16.01|en-US.

这样的字符串

请注意 即将推出的 API 提供了正式的 API 来获取此类信息。

规格link:https://github.com/OfficeDev/office-js-docs/tree/ContextAdditions_OpenSpec

这是获取所需信息的更好方法,而不是依赖 URL 查询字符串或会话存储。这种方法有点冒险,因为潜在的行为可能会在没有警告的情况下发生变化。使用已发布的 APIs 始终是一个不错的选择。