Search code examples
office-jsword-addins

"Word object is undefined" in Office 2016 add-in after login redirection


I'm trying to make a word add in that first must redirect to a login page after initially loading and after logging in redirects back to the add in. The add in is hosted on its own web server. However, after the redirect, I get an error that "Word is undefined". The add in is running inside of word, and I have calls to Office.initialize and Word.run. If I run the add in so that it points back to localhost, instead of the web server for the add in, it runs fine, but when it runs from the web server I get the errors.

Here is what my code looks like for the page that gets the error:

(function () {
"use strict";

Office.initialize = function (reason) {
    $(document).ready(function () {

        try {
            doSomethingInWord();
        } catch (e) {
            console.log(e);
        }
    }
}
})();

My "doSomethingInWord" function looks like this:

function doSomethingInWord() {
    Word.run(function (context) {
        var body = context.document.body;

        return context.sync()
            .then(function () {
                    body.clear();
                    return context.sync().then(function () {
                        console.log('Did Something in word');
                    })
        }).catch(errorHandler);
    }
}

Solution

  • I think the issue you're seeing is that by redirecting to an auth dialog and back, you are somehow not re-triggering Office.js.

    I am surprised that you say it works for you in Word without Visual Studio -- I don't know how they would be related. But in either case, I think you'll run into other issues in this flow, especially in Excel Online, where the add-in runs in an iframe (and where OAuth dialogs tend to not allow being in an iframes).

    I think your best bet would be to load the add-in "normally", and use the Office.context.ui.displayDialogAsync API to display the OAuth login in a separate dialog. During this time, have your add-in show "waiting on dialog input for login". Then, have the dialog message back the parent once the OAuth login is complete, passing in any required info (token or whatnot).