Excel插件教程中commands.js内action函数引发的功能调用异常
Excel插件命令函数调用问题解答
1. action函数是否应该存在于Excel插件项目中?
不应该。这个自动生成的action函数是Outlook插件专属代码,完全不适用于Excel插件:
- 它依赖
Office.MailboxEnums枚举,该枚举仅在Outlook的Office.js运行环境中存在,Excel环境下无此对象; - 代码中调用的
Office.context.mailbox.item.notificationMessages是Outlook特有的API,Excel插件的Office.context对象根本没有mailbox属性。
这属于Yeoman Office插件模板的疏漏——模板复用逻辑错误,将Outlook的示例代码混入了Excel项目模板。你可以直接删除整个action函数及其相关的全局挂载代码(g.action = action;),不会对Excel插件的功能产生任何影响。
2. 为何toggleProtection函数置于action下方会调用失败?
核心原因是action函数内部的代码在Excel环境下会触发隐性运行时错误,导致后续代码无法执行:
当Excel加载commands.js时,脚本从上到下执行:
- 若
toggleProtection函数及Office.actions.associate关联代码位于action函数之后,脚本解析到action函数内部的Office.MailboxEnums时,部分Office宿主的脚本引擎会因该对象不存在触发隐性错误,中断后续代码执行; - 此时
toggleProtection函数的定义和关联操作都未完成,功能区按钮点击时无法找到对应函数,导致调用失败。
将toggleProtection相关代码移至action函数上方后,这部分代码在错误触发前已执行完毕,函数关联生效,因此能够正常响应按钮点击。
修正后的commands.js代码(移除无效的Outlook专属代码)
/* * Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT license. * See LICENSE in the project root for license information. */ /* global global, console, Excel, Office, OfficeExtension, self, window */ Office.onReady(() => { // If needed, Office.js is ready to be called console.log("We're in commands.js!!!"); }); async function toggleProtection(args) { await Excel.run(async (context) => { console.log("we've entered toggleProtection!!!"); const sheet = context.workbook.worksheets.getActiveWorksheet(); sheet.load("protection/protected"); await context.sync(); if (sheet.protection.protected) { sheet.protection.unprotect(); } else { sheet.protection.protect(); } await context.sync(); }).catch(function (error) { console.log("Error: " + error); if (error instanceof OfficeExtension.Error) { console.log("Debug info: " + JSON.stringify(error.debugInfo)); } }); args.completed(); } Office.actions.associate("toggleProtection", toggleProtection); function getGlobal() { return typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : typeof global !== "undefined" ? global : undefined; } const g = getGlobal(); // 移除Outlook专属的action函数全局挂载
内容的提问来源于stack exchange,提问作者TheNewGuy
相关产品推荐
相关产品推荐

