Leo
Leo

Reputation: 5122

Long operations crash Office addin (JS)

I just created a (JS) Word Add-in and found that long synchronous operations can make it crash. In these cases, the following error is displayed - [ADD-IN ERROR Sorry, we had to restart because this add-in wasn't responding.]

enter image description here

The following code is ran on a button click.

    function scanText() {

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

            context.load(body, 'text');

            return context.sync().then(function () {
                
                var r = thisOperationCanTakeALongTimeIfDocIsLarge(body.text);

            });
        })
        .catch(errorHandler);
    }

How do I prevent this from happening? should I make the long operation asynchronous? How is this achieved in this context?

Upvotes: 3

Views: 1191

Answers (1)

Leo
Leo

Reputation: 5122

I have finally found a good way to solve this... I use a WebWorker like so:

    function scanText() {
        var w;

        if (typeof (w) == "undefined") {
            w = new Worker("./Scripts/myWebWorker.js");
        }
        else
        {
            showNotification("Sorry! No Web Worker support.");
        }

        w.onmessage = function (event) {
            showNotification(event.data);
        };

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

            context.load(body, 'text');

            return context.sync().then(function () {
                w.postMessage(body.text);
            });
        })
        .catch(errorHandler);
    }

And the myWebWorker.js file:

self.importScripts([...some scripts i need...]);

self.addEventListener("message", function (e) {
    var r = thisOperationCanTakeALongTimeIfDocIsLarge(e.data);
    postMessage(r);
}, false);

Upvotes: 4

Related Questions