Office JS Word:网页版创建文档后无法编辑自定义属性求解决方案
问题
我尝试用Office JS在Word中创建新文档后设置自定义属性,代码如下:
Word.run(context => { const createdDoc = context.application.createDocument(file); context.load(createdDoc.properties.customProperties); createdDoc.properties.customProperties.add("Test", 42); return context .sync() .then(() => { createdDoc.open(); }) });
这段代码在桌面版Word运行正常,但Office网页版会报错,求解决办法。
解决思路与代码
网页版Word的机制限制了对未打开的新创建文档的属性操作,必须先打开文档,待其成为活动文档后再处理属性。
修改后的兼容代码:
Word.run(context => { const createdDoc = context.application.createDocument(file); return context.sync() .then(() => createdDoc.open()) .then(() => { // 切换到活动文档的上下文进行属性操作 return Word.run(activeContext => { const activeDoc = activeContext.document; activeContext.load(activeDoc.properties.customProperties); return activeContext.sync() .then(() => { activeDoc.properties.customProperties.add("Test", 42); return activeContext.sync(); }); }); }); });
关键说明
- 网页版中,未打开的文档未完成初始化,无法访问其属性集合
- 必须等文档打开后,通过
activeContext.document获取当前活动文档来操作属性 - 该写法同时兼容桌面版和网页版Word
内容的提问来源于stack exchange,提问作者PlantyPy
相关产品推荐
相关产品推荐

