问题
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