Posted by on Nov 19, 2015 in #Office365Dev | 0 comments

Sharing code across different environments is always a good thing – it helps us to maintain the project, hunt bugs and deliver a consistent experience. If you are building add-ins for Excel and Word using the Office.js library (https://msdn.microsoft.com/en-us/library/office/fp142185.aspx) – we have the ability to create a single codebase for both of the two worlds.

The API contains functions that works great in both Excel and Word.

But sometimes you might be interested in creating slightly different behaviors, depending on the host application that your add-in is running within.

Why is this useful? Say that you are inserting data into the Office context. In some cases, it would make more sense to insert it as tables in Excel, but as paragraphs for Word. It’s a slight adjustment to make in a shared codebase.

To do that, you will need to be able to distinguish between them, Excel and Word in this case. Luckily there is a very solid way of doing so, simply by detecting which API set that is available to you.

I created the following logic to detect the host application, it is using a new API that we released with the new Excel and Word APIs. The function Office.context.requirements.isSetSupported let’s you detect at runtime if a particular API set is available.

At first, we try to see if the API version 1.1 is available (as in Office 2016 and Office Online). If it’s not – we look for the API version 1.0 (Office 2013). As long as you are grabbing the Office.js library via the CDN (https://appsforoffice.microsoft.com/lib/1/hosted/office.js) – this new functionality should be available for you to use.

Once your initialize function has been called by the Office.js library – you can call the getHostInfo function and extract the information.

This is the log I received from running an Excel add-in in Excel 2016 for Windows desktop.

excelwordhost

Like so you can create the host-specific code you need for your Excel and Word add-ins – yet still maintain a shared codebase.

If you strongly depend on specific API sets in your Office add-ins, I would encourage you to define this in your manifest file. Doing that will allow us to present a better experience to users (before runtime), for instance by simply not allowing your add-in to be inserted into a context where it simply cannot operate. Read more at: https://msdn.microsoft.com/en-us/library/office/dn535871.aspx#SpecifyRequirementSets_minversion

-Simon Jaeger