I am building a JS add-in that simply forwards a message with the added comment 'STOP' to a defined address upon clicking a button in the ribbon. In order to forward I call the REST API with a POST
request.
When adding event.completed()
at the end of the function, with (event)
as parameter, the getCallbackTokenAsync does not run at all.
Instead, without it, the add-in forwards the message properly but the info bar does not disapear and the script keeps running on a loop:
Info bar to signal that script is running: https://i.sstatic.net/zGa2K.png
Any ideas on how I should properly handle the event.completed()
when calling the REST API?
// the function sendAsStops is called directly from the manifest file
function sendAsStops(event) {
console.log("Initialising STOP command.");
var restHost = Office.context.mailbox.restUrl;
var itemId = getItemRestId();
console.log(itemId);
Office.context.mailbox.getCallbackTokenAsync({ isRest: true }, function (result) {
if (result.status === Office.AsyncResultStatus.Succeeded) {
console.log('Sending email...');
var accessToken = result.value;
console.log(result);
var getMessageUrl = restHost + '/v2.0/me/messages/' + itemId + '/forward';
$.ajax({
url: getMessageUrl,
type: 'post',
headers: { 'Authorization': 'Bearer ' + accessToken },
contentType: 'application/json',
dataType: 'json',
data: JSON.stringify({
'Comment': 'STOP',
'ToRecipients': [{'EmailAddress': { 'Address': '[email protected]' }}],
})
}).done(function() {
console.log("Stop successfully forwarded.");
}).fail(function(error) {
console.log("Failed to send");
});
} else {
console.log("Unable to proceed. Ref: " + result.status);
return false;
}
});
event.completed();
}
function getItemRestId() {
console.log("Getting item ID...");
if (Office.context.mailbox.diagnostics.hostName === 'OutlookIOS') {
console.log("ID ready to use.");
return Office.context.mailbox.item.itemId;
} else {
console.log('Converting ID...');
return Office.context.mailbox.convertToRestId(
Office.context.mailbox.item.itemId,
Office.MailboxEnums.RestVersion.v2_0
);
}
}
event.completed()
must be called at the end of the execution of your add-in. Calling event.completed()
is terminating your add-in, so any asynchronous calls (such as getCallbackTokenAsync
callback in this case) gets automatically terminated and cleaned up. Hence, you do not see the add-in forwarding the message.
Call event.completed()
after your entire add-in execution is complete. Something like:
$.ajax({
url: getMessageUrl,
type: 'post',
headers: { 'Authorization': 'Bearer ' + accessToken },
contentType: 'application/json',
dataType: 'json',
data: JSON.stringify({
'Comment': 'STOP',
'ToRecipients': [{'EmailAddress': { 'Address': '[email protected]' }}],
})
}).done(function() {
console.log("Stop successfully forwarded.");
event.completed();
}).fail(function(error) {
console.log("Failed to send");
event.completed();
});