检查 Office.js 是否在 Office 客户端之外加载

Check if Office.js is loaded outside of Office client

如果我们在 Office 客户端之外加载引用 office.js 的网页,我们将收到警告:Office.js is loaded outside of Office client.

此信息很有用。

有人知道我的代码中是否有 API 来检查吗?

编辑 1:

我稍微解释一下我的情况以及我问这个问题的原因。我正在制作一个带有 angularjs 的应用程序,它可以作为网页加载到浏览器中,也可以作为加载项加载到 Office 中。而且我意识到我们不应该一起做<body ng-app="myApp">angular.bootstrap(document, ['myApp']),否则控制器会执行两次。所以我决定不写 <body ng-app="myApp"> 并且在两种情况下(即网页和加载项)始终使用 angular.bootstrap

所以对于网页,我可以这样写:

$(document).ready(function () {
    angular.bootstrap(document, ['myApp'])  
})

app = angular.module('myApp', ['ui.router', 'ui.bootstrap'])
...

所以对于一个网页,我需要在Office.initialize里面写angular.bootstrap,其他的代码与add-in的情况共享:

Office.initialize = function (reason) {
    $(document).ready(function () {
        angular.bootstrap(document, ['myApp'])
    });
}

app = angular.module('myApp', ['ui.router', 'ui.bootstrap'])
// share the same code

但是,如果我将这两种情况按如下方式写在一起,它适用于网页,而我给出 错误:ng:btstrpd 应用程序已使用此元素 用于加载项

$(document).ready(function () {
    angular.bootstrap(document, ['myApp'])
    console.log("bootstrapped outside Office.initialize")   
})

Office.initialize = function (reason) {
    $(document).ready(function () {
        angular.bootstrap(document, ['myApp'])
        console.log("bootstrapped inside Office.initialize")
    })
}

app = angular.module('myApp', ['ui.router', 'ui.bootstrap']).

如果我设置了一个标志,控制台将显示 bootstrapped outside Office.initialize 后跟 isBootstrapped,然后 运行 代码将显示 Office.contextOffice.context.document 未定义:

var isBootstrapped = false;

$(document).ready(function () {
    angular.bootstrap(document, ['myApp'])
    isBootstrapped = true
    console.log("bootstrapped outside Office.initialize")
})

Office.initialize = function (reason) {
    $(document).ready(function () {
        if (isBootstrapped) console.log("isBootstrapped")
        else {
            angular.bootstrap(document, ['myApp'])
            console.log("bootstrapped inside Office.initialize")
        }
    })
}

app = angular.module('myApp', ['ui.router', 'ui.bootstrap'])

所以我真的需要一种有效的方法来检查 Office.js 是否在 Office 客户端之外加载(即,它是网页还是加载项),以确定 angular.bootstrap 应该被执行。

目前没有这样的 API,尽管我们内部讨论过有一个 Office.ready()(在精神上类似于 $(document).ready(...)),它会在任何时候触发 Office.js 已完成初始化(无论是否在加载项中)。

欢迎您在 https://github.com/OfficeDev/office-js 上提出建议,并在 post 和 link 上提出建议。我对 API 的想法是它会接受一个回调(就像 $(document).ready(...) 它会在准备就绪时触发,并且也可以以承诺的形式提供(所以你可以做 await Office.ready() ). 你认为这适用于你的场景吗?

FWIW:作为解决方法,Script Lab, we wrap a Promise around Office.initialized (and make sure to do it early on in the loading of the application, else it won't fire if it's much later), wait for it, and if we don't receive anything in the first 3 seconds we show a set of buttons to let the user help disambiguate for us. See https://script-lab.azureedge.net/ 提供了一个示例。不完美,但对我们的场景来说还可以。不过,我确实鼓励您在 office-js 存储库上提交一个建议错误,添加您的具体场景来支持它。

一种方法是使用 https://github.com/OfficeDev/office-js-helpers.

OfficeHelpers.Utilities.hostOfficeHelpers.Utilities.platform 都提供了有用的信息。