Long operations crash Office addin (JS)

帅比萌擦擦* 提交于 2021-02-04 08:03:08

问题


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.]

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?


回答1:


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);


来源:https://stackoverflow.com/questions/42438093/long-operations-crash-office-addin-js

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!