有没有办法判断您的应用程序在 Microsoft Teams 中是否 运行

Is there a way to tell if your app is running in Microsoft Teams

我有一个 Web 应用程序需要执行特定代码,如果它在 Microsoft Teams 中 运行ning,但是我还没有想出是否有任何方法可以判断您的应用程序是否 运行组队。有什么想法或见解吗?

编辑:

如果有人想知道我们最终使用了以下两个答案的组合,在应用程序启动时,它会检查应用程序的 url 以查看它是否包含“/teams”。团队应用被明确告知指向 {app_name}/teams,如果这种情况属实,它将 运行 以下代码块:

import * as microsoftTeams from '@microsoft/teams-js';


if (window.location.pathname.includes('teams')) {
    microsoftTeams.initialize(() => {
      microsoftTeams.getContext(context => {
        store.dispatch(teamsDetected(context.hostClientType!));
        try {
          microsoftTeams.settings.registerOnSaveHandler(saveEvent => {
            microsoftTeams.settings.setSettings({
              websiteUrl: window.location.href,
              contentUrl: `${window.location.href}&teams`,
              entityId: context.entityId,
              suggestedDisplayName: document.title
            });
            saveEvent.notifySuccess();
          });
          microsoftTeams.settings.setValidityState(true);
        } catch (err) {
          console.error('failed to set teams settings')
        }
      });
    });
  }

正如您可能经历过的那样,如果您 不在 Teams 中,那么对 microsoftTeams.getContext(...) 的调用永远不会 return。

所以我有一个标志,我用 setInterval 监视它,如果 this._teamsContext 是真实的,并且具有合理的值;并且只有当有 this._hasAttemptedConnection

有点迂回的方式。

我稍后实施的另一种机制是传递带有 URL 入口点的标志(在我们的例子中:这是一个 Teams 选项卡)https://<oururl>?context=teams 并且仅在 Teams 中使用 Teams 代码路径.

我在 Microsoft Teams .js 中看到请求 github 到 return 来自 microsoftTeams.getContext(...) 的失败参考:is there any API to detect running in Teams or not?

在标记之前,我有一些 Typescript 代码看起来像

 WireTeams(): Promise<boolean> {
        this._hasAttemptedConnection = false
        return new Promise<boolean>((resolve, reject) => {
            microsoftTeams.initialize()
            microsoftTeams.getContext((context) => {
                if (context === null || context === undefined) {
                    resolve(false)
                }
                this._teamsContext = context
              })
           })
       this._hasAttemptedConnection = true
}