You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Word 365纯JS Web加载项MSAL登录遇interaction_in_progress错误如何处理

Word 365 桌面端JS加载项Msal登录问题解决方案

核心原因

你当前遇到的问题本质是桌面端Office加载项运行在嵌入式WebView中,loginRedirect触发的跳转被系统默认浏览器(Chrome)捕获,整个登录流程在外部浏览器完成,重定向结果也没有返回加载项所在的WebView,因此handleRedirectPromise无法触发,同时WebView本地存储中残留了交互进行中的标记,导致二次登录抛出如下错误:

interaction_in_progress: Interaction is currently in progress. Please ensure that this interaction has been completed before calling an interactive API.


具体调整步骤

    1. 优先使用弹窗流替代重定向流
      桌面端WebView环境下弹窗流适配性更好,不会被系统浏览器截胡,且不需要处理跨上下文的回调传递。
    1. 补充Msal初始化必要逻辑
      Msal v2版本要求实例化后先调用initialize()方法完成初始化,再执行后续交互逻辑。
    1. 修正Msal配置项
      确保redirectUri和Azure AD应用注册的地址完全一致,且为加载项同源地址;添加iframe内运行的适配配置。
    1. 增加交互状态异常清理逻辑
      初始化时检查残留的交互状态,避免误报交互进行中的错误。

修正后完整代码

let myMSALObj = null;
// 登录请求配置
const loginRequest = {
    scopes: ['user.read', 'files.read.all']
};

window.Office.onReady(async () => {
    await initMsalInstance();
});

async function initMsalInstance() {
    myMSALObj = new msal.PublicClientApplication({
        auth: {
            clientId: "你的Azure AD应用客户端ID",
            authority: "https://login.microsoftonline.com/你的租户ID或者common",
            redirectUri: "你的加载项页面地址,和Azure注册的完全一致",
            navigateToLoginRequestUrl: true
        },
        cache: {
            cacheLocation: 'localStorage',
            storeAuthStateInCookie: false // 桌面WebView无需兼容IE,可关闭
        },
        system: {
            allowRedirectInIframe: true, // 适配加载项运行在iframe的场景
            loggerOptions: {
                loggerCallback: (level, message, containsPii) => {
                    if (containsPii) return;
                    console.log(`MSAL日志: ${message}`);
                }
            }
        }
    });

    // 必须先调用initialize完成初始化
    await myMSALObj.initialize();

    // 初始化时清理残留的交互状态,避免报错
    if (myMSALObj.getActiveAccount() == null && myMSALObj.getAllAccounts().length > 0) {
        myMSALObj.setActiveAccount(myMSALObj.getAllAccounts()[0]);
    }
    // 检查是否有未完成的交互,清理异常状态
    if (localStorage.getItem('msal.interaction.status')) {
        await myMSALObj.clearCache();
    }

    // 如果你坚持使用重定向流,保留该回调,用弹窗流可省略
    myMSALObj.handleRedirectPromise()
        .then((response) => {
            if (response) {
                console.log('获取到令牌响应:', response);
                // 这里可以处理token,存储或者调用Graph
            }
        })
        .catch((error) => {
            console.error('重定向处理错误:', error);
            await myMSALObj.clearCache();
        });
}

// 改用弹窗登录方法
async function signIn() {
    try {
        // 先尝试静默获取token,无需用户交互
        const activeAccount = myMSALObj.getActiveAccount();
        if (activeAccount) {
            const silentResponse = await myMSALObj.acquireTokenSilent({
                ...loginRequest,
                account: activeAccount
            });
            console.log('静默获取到令牌:', silentResponse);
            return silentResponse;
        }
        // 静默失败则调用弹窗登录
        const popupResponse = await myMSALObj.loginPopup(loginRequest);
        console.log('弹窗登录成功,获取到令牌:', popupResponse);
        myMSALObj.setActiveAccount(popupResponse.account);
        return popupResponse;
    } catch (error) {
        console.error('登录失败:', error);
        // 交互被取消等场景清理状态
        await myMSALObj.clearCache();
    }
}

额外验证项

  • 检查Azure AD应用注册的重定向URI类型设置为单页应用(SPA),不能是Web应用
  • 确保加载项的域名已添加到Azure AD应用的重定向URI列表中
  • 桌面端Office建议升级到最新版本,使用Edge WebView2作为运行环境,兼容性更好

内容的提问来源于stack exchange,提问作者IKIKN

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.01 12:54:01