Taskpane Word Add-ins(Office-JS)在Word 365在线版搜索返回空对象问题
Word 365在线版Taskpane加载项搜索返回空对象,桌面版功能正常
我用React+TypeScript开发了一款Word任务窗格加载项,功能是搜索文档中的词汇列表并替换为新词汇。桌面版MS Word里所有功能都正常,能找到全部目标词汇;但部署到Word 365在线版后,任务窗格能正常加载,点击搜索按钮却找不到任何内容,搜索函数始终返回空对象{}。
核心搜索代码如下(桌面版正常,在线版异常):
(async () => { try { let options = Word.SearchOptions.newObject(context); options.matchCase = false; options.matchWholeWord = true; options.ignorePunct = true; await Promise.all( WordList.map(async (data: customWord) => { // NOTE: In Word 365 online, searchResults is always {} const searchResults = textSelected ? context.document.getSelection().search(data.word, options) : context.document.body.search(data.word, options); searchResults.load("items, text"); allSearchResults.push(searchResults); }) ); } catch (error) { console.error(error); } })();
请问为什么Word在线版中搜索结果为空?是否和浏览器环境下的Promise.all()使用有关?
问题原因及解决办法
缺少
context.sync()同步调用
Office JavaScript API的所有数据加载操作都需要通过context.sync()来触发实际的数据获取。桌面版Word可能对未同步的加载有容错处理,但在线版严格要求显式执行同步,否则只会得到空的占位对象。Promise.all使用逻辑错误
当前map中的异步函数没有返回有效Promise,Promise.all实际等待的是一堆空Promise,导致代码提前执行完成,而搜索结果还未同步回来。
修正方案1:统一批量同步(性能更优)
(async () => { try { let options = Word.SearchOptions.newObject(context); options.matchCase = false; options.matchWholeWord = true; options.ignorePunct = true; // 先创建所有搜索请求并标记需要加载的属性 WordList.forEach((data: customWord) => { const searchResults = textSelected ? context.document.getSelection().search(data.word, options) : context.document.body.search(data.word, options); searchResults.load("items, text"); allSearchResults.push(searchResults); }); // 统一执行同步操作,一次性获取所有搜索结果 await context.sync(); } catch (error) { console.error(error); } })();
修正方案2:单个搜索请求单独同步(适合需并行处理结果的场景)
(async () => { try { let options = Word.SearchOptions.newObject(context); options.matchCase = false; options.matchWholeWord = true; options.ignorePunct = true; await Promise.all( WordList.map(async (data: customWord) => { const searchResults = textSelected ? context.document.getSelection().search(data.word, options) : context.document.body.search(data.word, options); searchResults.load("items, text"); allSearchResults.push(searchResults); // 每个搜索请求单独执行同步 await context.sync(); }) ); } catch (error) { console.error(error); } })();
关键说明
- 在线版Office对API调用的同步要求比桌面版更严格,所有涉及数据读取的操作必须显式调用
context.sync()。 - 批量操作时,统一调用一次
context.sync()比多次调用的性能更好,建议优先采用第一种方案。
内容的提问来源于stack exchange,提问作者Meisam Mofidi
相关产品推荐
相关产品推荐

