JavaScript Snippets
Insert some text
doc.body.insertText("This is me inserting some text into my document. \n", "Start")
doc.body.getRange('Content').select();
doc.body.search("document",{matchCase:true, matchWholeWord:true}).getFirst().select();
let myResults = doc.body.search("document", { matchCase: true, matchWholeWord: true })
myResults.load(['items','text']);
await context.sync();
myResults.items.forEach(function(rng){
console.log(rng.text)
})
doc.body.load(['style']);
await context.sync();
insert base64 encoded .docx at the beginning of the content body.
var body = ctx.document.body;
body.insertFileFromBase64(getBase64(), Word.InsertLocation.start);
save a document
Word.run(function (context) {
var thisDocument = context.document;
context.load(thisDocument, 'saved');
return context.sync().then(function () {
if (thisDocument.saved === false) {
// Queue a command to save this document.
thisDocument.save();
return context.sync().then(function () {
console.log('Saved the document');
});
} else {
console.log('The document has not changed since the last save.');
}
});
})
Built-in Document Properties
$("#run").click(() => tryCatch(getProperties));
async function getProperties() {
await Word.run(async (context) => {
let builtInProperties = context.document.properties;
builtInProperties.load("*"); // Let's get all!
await context.sync();
console.log(JSON.stringify(builtInProperties, null, 4));
});
}
async function tryCatch(callback) {
try {
await callback();
} catch (error) {
console.error(error);
}
}
Custom Document Properties
$("#number").click(() => tryCatch(insertNumericProperty));
$("#string").click(() => tryCatch(insertStringProperty));
$("#read").click(() => tryCatch(readCustomDocumentProperties));
async function insertNumericProperty() {
await Word.run(async (context) => {
context.document.properties.customProperties.add("Numeric Property", 1234);
await context.sync();
console.log("Property added");
});
}
async function insertStringProperty() {
await Word.run(async (context) => {
context.document.properties.customProperties.add("String Property", "Hello World!");
await context.sync();
console.log("Property added");
});
}
async function readCustomDocumentProperties() {
await Word.run(async (context) => {
let properties = context.document.properties.customProperties;
properties.load("key,type,value");
await context.sync();
for (var i = 0; i < properties.items.length; i++)
console.log(
"Property Name:" +
properties.items[i].key +
"; Type=" +
properties.items[i].type +
"; Property Value=" +
properties.items[i].value
);
});
}
async function tryCatch(callback) {
try {
await callback();
} catch (error) {
console.error(error);
}
}
Document Assembly
$("#insert-header").click(() => tryCatch(insertHeader));
$("#add-paragraphs").click(() => tryCatch(addParagraphs));
$("#add-content-controls").click(() => tryCatch(addContentControls));
$("#change-customer").click(() => tryCatch(changeCustomer));
$("#add-footer").click(() => tryCatch(addFooter));
async function insertHeader() {
await Word.run(async (context) => {
let header = context.document.body.insertText(
"This is a sample Heading 1 Title!!\n",
"Start" /*this means at the beginning of the body */
);
header.styleBuiltIn = Word.Style.heading1;
await context.sync();
});
}
async function addParagraphs() {
await Word.run(async (context) => {
let paragraph = context.document.body.insertParagraph("Timeline", "End");
paragraph.style = "Heading 2";
let paragraph2 = context.document.body.insertParagraph(
"The Services shall commence on July 31, 2015, and shall continue through July 29, 2015.",
"End"
);
paragraph2.style = "Normal";
let paragraph3 = context.document.body.insertParagraph("Project Costs by Phase", "End");
paragraph3.style = "Heading 2";
let paragraph4 = context.document.body.insertParagraph("<Add Project Costs Here>", "End");
paragraph4.style = "Normal";
paragraph4.font.highlightColor = "#FFFF00";
let contentControl = paragraph4.insertContentControl();
contentControl.title = "ProjectCosts";
let paragraph5 = context.document.body.insertParagraph("Project Team", "End");
paragraph5.style = "Heading 2";
paragraph5.font.highlightColor = "#FFFFFF";
let paragraph6 = context.document.body.insertParagraph("Terms of Work", "End");
paragraph6.style = "Heading 1";
let paragraph7 = context.document.body.insertParagraph(
"Contractor shall provide the Services and Deliverable(s) as follows:",
"End"
);
paragraph7.style = "Normal";
let paragraph8 = context.document.body.insertParagraph("Out-of-Pocket Expenses / Invoice Procedures", "End");
paragraph8.style = "Heading 2";
let paragraph9 = context.document.body.insertParagraph(
"Client will be invoiced monthly for the consulting services.",
"End"
);
paragraph9.style = "Normal";
context.document.body.insertBreak("Page", "End");
await context.sync();
});
}
async function addContentControls() {
await Word.run(async (context) => {
let results = context.document.body.search("Contractor");
results.load("font/bold");
let customerContentControls = context.document.contentControls.getByTag("customer");
customerContentControls.load("text");
await context.sync();
if (customerContentControls.items.length === 0) {
for (var i = 0; i < results.items.length; i++) {
results.items[i].font.bold = true;
var cc = results.items[i].insertContentControl();
cc.tag = "customer"; // This value is used in the next step of this sample.
cc.title = "Customer Name " + i;
}
}
await context.sync();
});
}
async function changeCustomer() {
await Word.run(async (context) => {
let contentControls = context.document.contentControls.getByTag("customer");
contentControls.load("text");
await context.sync();
for (let i = 0; i < contentControls.items.length; i++) {
contentControls.items[i].insertText("Fabrikam", "Replace");
}
await context.sync();
});
}
async function addFooter() {
await Word.run(async (context) => {
context.document.sections
.getFirst()
.getFooter("Primary")
.insertParagraph("Confidential", "End");
await context.sync();
});
}
async function tryCatch(callback) {
try {
await callback();
} catch (error) {
console.error(error);
}
}
Set Multiple Properties at Once
$("#set-multiple-properties-with-object").click(() => tryCatch(setMultiplePropertiesWithObject));
$("#copy-properties-from-paragraph").click(() => tryCatch(copyPropertiesFromParagraph));
$("#setup").click(() => tryCatch(setup));
async function setMultiplePropertiesWithObject() {
await Word.run(async (context) => {
const paragraph = context.document.body.paragraphs.getFirst();
paragraph.set({
leftIndent: 30,
font: {
bold: true,
color: "red"
}
});
await context.sync();
});
}
async function copyPropertiesFromParagraph() {
await Word.run(async (context) => {
const firstParagraph = context.document.body.paragraphs.getFirst();
const secondParagraph = firstParagraph.getNext();
firstParagraph.load("text, font/color, font/bold, leftIndent");
await context.sync();
secondParagraph.set(firstParagraph);
await context.sync();
});
}
async function setup() {
await Word.run(async (context) => {
context.document.body.clear();
context.document.body.insertParagraph(
"Video provides a powerful way to help you prove your point.",
"Start"
);
context.document.body.paragraphs
.getLast()
.insertText(
"To make your document look professionally produced.",
"Replace"
);
});
}
async function tryCatch(callback) {
try {
await callback();
} catch (error) {
console.error(error);
}
}
async function performSearch() {
let searchTerm = <...>;
await Word.run(async (context) => {
let searchItems = context.document.body.search(
searchTerm, {matchCase: false, matchWholeWord: true});
searchItems.load("text");
await context.sync();
let fullSentences: Word.Range[] = [];
searchItems.items.forEach(range => {
let sentence = range.getTextRanges(
[".", "?", "!", ",", ";"]).getFirst();
sentence.load("text");
fullSentences.push(sentence);
});
await context.sync();
let $searchResults = $("#search-results").empty();
fullSentences.forEach(range => {
let $button = $("<a href='javascript:void(0)'>")
.text(range.text)
.click(() =>
tryCatch(() => selectAndFormatRange(range)));
$searchResults.append($button);
});
});
}
function selectAndFormatRange(range: Word.Range) {
console.log("TODO");
}
© 2026 Better Solutions Limited. All Rights Reserved. © 2026 Better Solutions Limited TopPrev