我正在使用word javascript api开发一个word插件,需要获取当前选择的contentControl,因此使用parentContentControl作为当前选择。
**Code:**
var range = context.document.getSelection().parentContentControl;
context.load(range);
但是在控制台上显示错误: 错误:
{"name":"OfficeExtension.Error","code":"GeneralException","message":"GeneralException","traceMessages":[],"debugInfo":{"errorLocation":"Range.parentContentControl"},"stack":"GeneralException: GeneralException\n at Anonymous function (https://appsforoffice.microsoft.com/lib/1/hosted/word-win32-16.01.js:19:189006)\n at pi (https://appsforoffice.microsoft.com/lib/1/hosted/word-win32-16.01.js:19:211583)\n at ht (https://appsforoffice.microsoft.com/lib/1/hosted/word-win32-16.01.js:19:211670)\n at g (https://appsforoffice.microsoft.com/lib/1/hosted/word-win32-16.01.js:19:211490)\n at l (https://appsforoffice.microsoft.com/lib/1/hosted/word-win32-16.01.js:19:210076)"}
Debug info: {"errorLocation":"Range.parentContentControl"}
如果当前选择不包含任何 contentControl 它应该返回 NULL,但它会给出错误。请指教。
谢谢。
这是一个非常好的问题,涉及到office.js技术的核心概念之一:我们如何处理null?长话短说,每当方法/属性有可能返回 null 时,我们都会提供该方法/属性的风格:
默认。没有特殊后缀。如果返回值为空(在这种情况下,没有围绕选择的内容控制),这种风格会立即引发异常,正如您的问题中所正确描述的那样。这是设计使然。
var myCC = context.document.getSelection().parentContentControlOrNullObject; // this flavor will not throw an exception.
context.load(myCC);
return context.sync()
.then(function () {
if (myCC.isNullObject) // when using this flavor of the property you will get a isNullObject to check if its null or not and act accordingly.
console.log("There is no content control sorrounding");
else
app.showNotification("there is a content control wrapping the selection.");
})
.catch(function (e) {
console.log(e.message);
})
})
这是Microsoft Office word 2016版本问题。 相同的代码在
16.0.7571.7095.
function insideOfContentControlCheck() {
Word.run(function (ctx) {
var myCC = ctx.document.getSelection().parentContentControl;
ctx.load(myCC); // I think this is the part you are missing!
return ctx.sync()
.then(function () {
console.log(myCC.title);// if there is a content control we'll show the title
});
}).catch(function (e) {
//there is no ContentControl.
console.log("Error", e.message);
});
}
这是检查
parentSectionOrNullObject
await Word.run(async (context) => {
let html;
const range = context.document.getSelection();
range.load('parentContentControlOrNullObject, parentTableOrNullObject');
await context.sync();
const contentControl = range.parentContentControlOrNullObject;
if (!contentControl.isNull) {
html = contentControl.getHtml();
}else{
console.log("there is not parentContentControlOrNullObject in current Selection")
}
await context.sync();
console.log(html.value);
})