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

gat*_*sby 5 microsoft-teams

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

编辑:

对于任何想知道我们最终使用下面两个答案的组合的人,在应用程序启动时,它会检查应用程序的 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')
        }
      });
    });
  }
Run Code Online (Sandbox Code Playgroud)

小智 6

microsoftTeams.getContext(...)正如您可能经历过的那样,如果您不在Teams 中,则永远不会返回呼叫。

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

这有点迂回。

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

我在 Microsoft Teams .js github 中看到了从引用返回失败的请求microsoftTeams.getContext(...)是否有任何 API 可以检测是否在 Teams 中运行?

在标记之前,我有一些 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
}
Run Code Online (Sandbox Code Playgroud)