生产环境下Excel自定义函数中OfficeRuntime API不可用的解决流程咨询
解决OfficeRuntime.auth.getAccessToken()报错及生产环境启用流程
1. 修正加载项清单配置
这是解决报错的核心,TypeError通常源于清单未正确声明运行时环境或权限:
- 启用Shared Runtime:在清单的
<VersionOverrides>-><Hosts>-><Host>-><AllFormFactors>下添加<Runtime>节点,必须使用Shared Runtime(Isolated Runtime无法访问OfficeRuntime API):
<Runtime> <Override type="javascript" resid="Functions.Script.Url" /> <Page> <SourceLocation resid="Functions.Page.Url" /> </Page> <Permissions>ReadWriteDocument</Permissions> <RuntimeMode>Shared</RuntimeMode> </Runtime>
- 声明Auth要求集:在清单根节点的
<Requirements>下添加Auth要求集,版本不低于1.1:
<Requirements> <Sets DefaultMinVersion="1.1"> <Set Name="Auth" MinVersion="1.1" /> <Set Name="ExcelApi" MinVersion="1.1" /> </Sets> </Requirements>
- 配置基础权限:在清单根节点的
<Permissions>中指定所需权限:
<Permissions>ReadWriteDocument</Permissions>
2. 调整自定义函数代码逻辑
确保代码在Shared Runtime上下文运行,并做基础存在性检查:
async function getToken() { if (typeof OfficeRuntime !== 'undefined' && OfficeRuntime.auth) { try { const token = await OfficeRuntime.auth.getAccessToken({ allowSignInPrompt: true }); return token; } catch (error) { console.error('获取令牌失败:', error); throw error; } } else { throw new Error('OfficeRuntime.auth API不可用,请检查清单配置'); } }
3. SharePoint清单部署验证
因清单发布在SharePoint,需确认:
- 清单已上传至SharePoint应用目录并完成发布。
- 租户管理员已将加载项部署到目标站点或整个租户。
- 加载项在Excel中正常安装,未被浏览器或Office客户端安全策略拦截。
4. 生产环境测试验证
- 在生产环境的Excel桌面版/网页版中测试自定义函数,确认
getAccessToken调用正常。 - 通过浏览器控制台或Office加载项调试工具排查残留的权限/加载错误。
- 桌面版Excel需确保版本支持Auth 1.1要求集(Office 365 2019年10月及以后版本)。
内容的提问来源于stack exchange,提问作者Carlos Alberto
相关产品推荐
相关产品推荐

