Office.js Office.context.ui.messageParent not working in Excel

Solution for Office.js Office.context.ui.messageParent not working in Excel
is Given Below:

We have an excel add-in hosted in azure where the Office.context.ui.messageParent API messages aren’t being sent/received on the desktop. There’s no errors, the message just doesn’t get caught at the event listener.

We use the dialog for MFA and we have it working locally for both desktop and web but when we deploy to a stage add-in hosted in azure this issue occurs just on the desktop.

This works:

  • dialog url (https://localhost:3000/dist/callback.html)
  • taskpane url (https://localhost:3000/dist/taskpane.html)

This doesn’t:

Surprisingly the DialogEventReceived is being triggered but not the message DialogMessageReceived.

callback.html:

<!DOCTYPE html>
<html>

<head>
    <meta charset="UTF-8"/>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge"/>
    <meta http-equiv="Expires" content="0"/>
    <meta http-equiv="Cache-Control" content="private, no-cache, no-store"/>
    <meta http-equiv="Pragma" content="no-cache"/>
    <meta http-equiv="Expires" content="-1"/>
    <title></title>
    <script type="text/javascript" src="https://appsforoffice.microsoft.com/lib/1.1/hosted/office.js"></script>
</head>

<body>
<script>
    if (window.opener)
        window.opener.postMessage({type: 'interstitial', url: document.location.href}, "*");

    Office.initialize = function (reason) {
        console.log("Sending auth complete message through dialog: " + document.location.href);
        Office.context.ui.messageParent(document.location.href);
    }
</script>
</body>
</html>

snippet of the taskpane.html where’s the event listener:

Office.context.ui.displayDialogAsync(url, {
    height: dim.height,
    width: dim.width,
    promptBeforeOpen: false
}, async (result) => {
    _loginDialog = result.value;
    _loginDialog.addEventHandler(Office.EventType.DialogMessageReceived, processMessage);
    _loginDialog.addEventHandler(Office.EventType.DialogEventReceived, (ev) => {
        console.log("## EVENT RECEIVED ##", ev);
    });
});

function processMessage(arg) {
    console.log("Message received in processMessage: " + JSON.stringify(arg));
    _lastCallback(arg.message);
    _loginDialog?.close();
    _loginDialog = null;
}

enter image description here

Based on Authenticate and authorize with the Office dialog API, the correct flow is:

The add-in should launch the page in the dialog in add-in’s domain, then redirect to the sign-in page, and then redirect to another page with the same domain as the first page in dialog again.

Otherwise, the messageParent API won’t work, because it only trust the domain of the page used in the displayDialogAsync() API. In your scenario, the sign-in page (launched first time in the dialog) and the callback page are in different domains, which causes the problem.

Thanks.