Yesterday we’ve seen the minimal code running to insert a bit of text at the selected Range using Word.RequestContext:
(() => {
async function MinimalWordmethod() {
// Create the client request context. You’ll do this for all Word add-ins.
var ctx = new Word.RequestContext();
// Do your things here, such as ..
var range = ctx.document.getSelection();
range.insertText("Test MinimalWordMethod", "After");
await ctx.sync();
}
MinimalWordmethod();
})();
If you look however at the boilerplate code that is generated with a clean Yeoman project you find that RequestContext is never used, but instead of this you see Word.run(async (context) => { … });
Why is this and what is the difference? Well, I looked into this and found the answer on a piece of documentation from Michael Zlatkovsky, member of the Office Extensibility Platform team, here:
http://buildingofficeaddins.com/run
Michael explains it in his documentation but is written for Excel, however as you can read on the same page it is fully compliant with Word.run.
Here is a quote from the page:
You can think of the Excel.run
as a boiler-plate preamble; it is the batch function that is the star of the show, but it needs a request context in order to start off the chain of OM calls. The Excel.run
call is simply a means to that end, as it creates a new request context that it passes into the batch function.
Reading this quote explains that by using the <host>.run function you start a batch process, without the trouble of creating your context by yourself. The run function will take care of this for you. So instead of the code where you create your own context object as seen in the snippet above you should be able to run the following code:
(() => {
async function MinimalWordmethod() {
// Create the client request context. You’ll do this for al Word add-ins.
await Word.run(async (context) => {
// Do your things here, such as ..
var range = context.document.getSelection();
range.insertText("Test run MinimalWordMethod", "After");
await context.sync();
});
}
MinimalWordmethod();
})();
How to get the new minimal code running
Go back to the Yeoman project from yesterdays post, open the project folder and open the file app.ts in the src source folder.
Replace all the code from this file as seen in the top snippet with the code from the second, new snippet above. Save it and start your Add-in ‘server’ by running npm start in the root of your project.
Opening Word, with the installed Add-in will still show you the Add-in button:
By clicking the button the Taskpane is showing, just like we’ve seen before, but now you should see the words “Test run MinimalWordMethod” in your document:
Without creating your own context the Word.run function created its own context and the code still works. As you can see this helps you to take some effort out of your hand.
To be continued …