长时间操作会导致 Office 插件 (JS) 崩溃 [英] Long operations crash Office addin (JS)

查看:22
本文介绍了长时间操作会导致 Office 插件 (JS) 崩溃的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚创建了一个 (JS) Word 插件,发现长​​时间的同步操作会导致它崩溃.在这些情况下,会显示以下错误 - [加载项错误抱歉,我们不得不重新启动,因为此加载项没有响应.]

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?

推荐答案

我终于找到了解决这个问题的好方法...我像这样使用 WebWorker:

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

还有 myWebWorker.js 文件:

And the myWebWorker.js file:

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

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

这篇关于长时间操作会导致 Office 插件 (JS) 崩溃的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆