OfficeDev / office-js

A repo and NPM package for Office.js, corresponding to a copy of what gets published to the official "evergreen" Office.js CDN, at https://appsforoffice.microsoft.com/lib/1/hosted/office.js.
https://learn.microsoft.com/javascript/api/overview
Other
670 stars 96 forks source link

Unable to load officejs in office dialog undefined is not an object (evaluating 'OSF.DDA.RichApi.richApiMessageManager.register') #3582

Open ermacaz opened 1 year ago

ermacaz commented 1 year ago

I have an excel officejs add-in. I want to open an asyncdialog. I am able to open it and point it to a url and the page its pointing to renders. However the officejs library on the page fails to load with the error TypeError: undefined is not an object (evaluating 'OSF.DDA.RichApi.richApiMessageManager.register') This is thrown from Excel-mac-16.00.js:13106 return OSF.DDA.RichApi.richApiMessageManager.register(r);

Your Environment

osx 13.1 arm64 Excel Desktop 16.75.2

Expected behavior

officejs loads successfully and allows me to use the messageParent api.

Current behavior

When the page loads officejs fails to import with the error Unhandled Promise Rejection: TypeError: undefined is not an object (evaluating 'OSF.DDA.RichApi.richApiMessageManager.register') from Excel-mac-16.00.js:13106 return OSF.DDA.RichApi.richApiMessageManager.register(r);

The message api is failing to initialize so I am unable to use it. I can still call things like Office.onReady(), but if I call in console OSF.DDA.RichApi it returns undefined due to error above.

Steps to reproduce

I think a mac is required to reproduce as the offending js file is named excel-mac-16.00.js

  1. save the following html to a file

    <html>
    <head>
    <script src="https://appsforoffice.microsoft.com/lib/1.1/hosted/office.js" type="text/javascript"></script>
     <script>
        Office.onReady();
    </script>
    </head>
    <body>
    test
    </body>
    </html>

    Set up a way to serve this over https.

  2. create an empty officejs excel taskpane react typescript project

  3. In app.tsx component add the following, replacing URL-TO-HTML-FILE with the full url to the hosted html above.

    function processMessage(arg) {
    console.log('i was messaged')
    console.log(arg.message);
    }
    
    const showDialog = () => {
    console.log('show dialog called')
    let dialog;
    Office.context.ui.displayDialogAsync('URL-TO-HTML-FILE', { height: 30, width: 20 },
      function (asyncResult) {
        if (asyncResult.status === Office.AsyncResultStatus.Succeeded) {
          dialog = asyncResult.value;
          dialog.addEventHandler(Office.EventType.DialogMessageReceived, processMessage);
        } else {
          console.error('Failed to open dialog:', asyncResult.error);
        }
      }
    );
    }
    //then render in component
    return (<Button onClick={showDialog}>Show dialog</Button>)
  4. Add <AppDomain> entry to manifest for hosted html url.

  5. Sideload add-in. Open add-in taskpane and click the Show Dialog Button which will open the dialog and render the test text. If you inspect the dialog to open the js console you will see the error for failure to initialize OfficeJs. If you run Office.context.ui.messageParent('testmessage'); the message will not make it to the taskpane's processMessage method.

Useful logs

image

mumarniaz commented 1 year ago

I'm also getting the same error when opening page inside dialog displayDialogAsync

image

coeguru commented 1 year ago

I am also facing the same issue, Any update on this ?

ermacaz commented 1 year ago

[sad un-initialized noises]

trigurl commented 1 year ago

Hi, I just created a simple taskpane with a button that launches the dialog on my Mac that with excel-mac-16.00.js and it's working for me. Are you still seeing the issue?

function ShowDialog(event) { // URL has to be HTTPS Office.context.ui.displayDialogAsync('https://www.YourWebsite.com/home.html', { height: 30, width: 20 }, function (asyncResult) { if (asyncResult.status == Office.AsyncResultStatus.Succeeded) { console.log('Dialog Launched'); console.log(asyncResult.value); } else { console.log(asyncResult.error.message); } } ); }

ermacaz commented 12 months ago

Yupp, same issue still persists image

image

ammanley commented 12 months ago

I've been getting this inexplicable error as well. I'm not sure if the error is happening for you to the same extent I'm seeing, but a workaround that I've found some success with is:

  1. Load up a asyncDialogBox without the OfficeJS runtime loaded
  2. Do things like take login information, display information, etc.
  3. Gather up the required info to message back to the taskpane, and redirect to another HTML page I have hosted that does include the OfficeJS runtime loaded. I send information via the redirecting URL parameters.
  4. Even though this page will load up and crash, it does (for me anyway) succeed in parsing the parameters, composing a JSON struct, and firing off a message to the main taskpane, at which point I just instantly close it to avoid confusing the user with the error screen.
trigurl commented 12 months ago

Hello, I noticed in your code has a typo (triple equal sign), can you please give my function here a try. When I click on a button from my taskpane, it will call this ShowDialog function. When I inspect my console log, I see that it has Succeeded with "Dialog Launched" and the value. I have no errors appearing in excel-mac-16.00.js. Please give this a try as it will help determine the team this issue should go to.

function ShowDialog(event) { // URL has to be HTTPS Office.context.ui.displayDialogAsync('https://www.yourwebsite.com/home.html', { height: 30, width: 20 }, function (asyncResult) { if (asyncResult.status == Office.AsyncResultStatus.Succeeded) { console.log('Dialog Launched'); console.log(asyncResult.value); } else { console.log(asyncResult.error.message); } } ); }

ermacaz commented 12 months ago

I've updated that conditional to the code below but it did not resolve or change the issue

if (asyncResult.status == Office.AsyncResultStatus.Succeeded) {
  console.log('Dialog Launched');
  console.log(asyncResult.value);
} else {
  console.log(asyncResult.error.message);
}
ermacaz commented 12 months ago

also noting that visiting the page in a browser the library loads successfully. pointing taskpane to that page library loads successfully. its only when pointing the dialog to the page that i see it fail to load.

trigurl commented 11 months ago

Hi ermacaz,

**"Pointing the dialog to the page that I it fail to load".

Do you mean this line is failing? Is it HTTPS with a valid certificate?

// URL has to be HTTPS Office.context.ui.displayDialogAsync('https://www.microsoft.com', { height: 30, width: 20 },

ermacaz commented 11 months ago

No, none of the application code is failing or throwing exceptions - the only error is coming from the OfficeJs excel-mac-16.00.js file. The site is behind https. The dialog opens, the page it points to renders and I can see the 'test' text

<html>
<head>
    <script src="https://appsforoffice.microsoft.com/lib/1.1/hosted/office.js" type="text/javascript"></script>
     <script>
        Office.onReady();
    </script>
  </head>
  <body>
    test
    </body>
</html>

but the officejs library linked in this html fails to fully initialize with the error Unhandled Promise Rejection: TypeError: undefined is not an object (evaluating 'OSF.DDA.RichApi.richApiMessageManager.register') so I am unable send a message from the dialog back to the taskpane app since the message api failed to load.

trigurl commented 11 months ago

Hello, ok I think I get it now, the URL you are passing to your dialog is this above and that is when you see the error. Let me give it a try.

trigurl commented 11 months ago

OK I am able to repro this, I've chimed in my colleagues.

trevjnels commented 10 months ago

@trigurl @ammanley @ermacaz Also experiencing this. Any update on the issue?

ammanley commented 10 months ago

Im afraid not. We have shipped this product to production for a while, just working around the problem. Our team has been unable to determine a root cause, likely culprit, or make sense of the error messaging despite our best efforts. We've taken it as just the cost of doing business to support Excel, unfortunately :(

trevjnels commented 10 months ago

Thanks @ammanley

coeguru commented 10 months ago

For me this happens only on desktop excel application (both on windows and mac) and if I reload the dialog (right click -> reload). The error goes away.

Screenshot 2023-11-17 at 11 54 37 AM
coeguru commented 10 months ago

Wow, the issue got resolved if I use Office.onReady instead of Office.initialize in the dialog code.

I changed the dialog code from

Office.initialize = () => {
  const searchParams = new URLSearchParams(window.location.search);

  const action = searchParams.get("action") as MSAuthAction | null;
  console.log("start");
  switch (action) {
    case MSAuthAction.LOGIN: {
      handleLogin();
      return;
    }
    case MSAuthAction.LOGOUT: {
      handleLogout();
      return;
    }
    case MSAuthAction.LOGOUT_SUCCESS: {
      handleLogoutSuccess();
      return;
    }
    default: {
      handleLogin();
      return;
    }
  }
};

to

Office.onReady(() => {
  const searchParams = new URLSearchParams(window.location.search);

  const action = searchParams.get("action") as MSAuthAction | null;

  switch (action) {
    case MSAuthAction.LOGIN: {
      handleLogin();
      return;
    }
    case MSAuthAction.LOGOUT: {
      handleLogout();
      return;
    }
    case MSAuthAction.LOGOUT_SUCCESS: {
      handleLogoutSuccess();
      return;
    }
    default: {
      handleLogin();
      return;
    }
  }
});
hdwatts commented 10 months ago

I'm encountering this issue. I cannot currently message the dialog from the parent. I can successfully message the parent from the dialog, but not vice versa.

image

Inside the dialog, My Office.isReady returns a successful object, and the addHandlerAsync also returns status: "succeeded"

jake-chambers commented 10 months ago

I also am having this issue

image
jankrynauw commented 6 months ago

I also get the same error. I have a callback.html page:

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <link rel="icon" href="icon-32.png" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Logging In... 5</title>
    <script>
        console.log("Loading Header...")
    </script>
    <script type="text/javascript" src="https://appsforoffice.microsoft.com/lib/1/hosted/office.js"></script>

</head>

<body>
    done.
</body>

<script>
    Office.onReady((info) => {
        console.log("Office ready", info);
        if (info.host === Office.HostType.Excel) {
            console.log("Loaded into Excel");
            const urlParams = new URLSearchParams(window.location.search);
            const code = urlParams.get('code');

            if (code) {
                try {
                    Office.context.ui.messageParent(code);
                } catch (error) {
                    console.error("Error sending message to parent:", error);
                }
            }
        }
    }).catch(error => {
        console.error("Error initializing Office:", error);
    });
</script>

</html>

And get the following error:

Screenshot 2024-03-27 at 20 52 30

jankrynauw commented 6 months ago

As per the documentation: Cross-domain messaging to the host runtime updating my Office.context.ui.messageParent(code); to Office.context.ui.messageParent(code, { targetOrigin: "*" }); resolved this error for me.

gaskaj commented 5 months ago

Same issue as @jankrynauw any resolution anyone found?

Office.context.ui.messageParent("SAMPLE", { targetOrigin: "*" }); - This did not resolve issue either

image

rluncasu commented 5 months ago

Hello, I noticed in your code has a typo (triple equal sign), can you please give my function here a try. When I click on a button from my taskpane, it will call this ShowDialog function. When I inspect my console log, I see that it has Succeeded with "Dialog Launched" and the value. I have no errors appearing in excel-mac-16.00.js. Please give this a try as it will help determine the team this issue should go to.

function ShowDialog(event) { // URL has to be HTTPS Office.context.ui.displayDialogAsync('https://www.yourwebsite.com/home.html', { height: 30, width: 20 }, function (asyncResult) { if (asyncResult.status == Office.AsyncResultStatus.Succeeded) { console.log('Dialog Launched'); console.log(asyncResult.value); } else { console.log(asyncResult.error.message); } } ); }

why whould === be a typo ? asyncResult.status is of type Office.AsyncResultStatus.Succeeded)

rluncasu commented 5 months ago

same issue, desktop office on mac

image
powlaa commented 5 months ago

Hi, is there any update on this or a workaround? I am facing the same issue and haven't found a way to handle this error gracefully. In most cases it just fails silently and messageParent is not working.

omrybass commented 2 weeks ago

Hi. I'm also getting the same error using the following html: image

Error received: image

gaskaj commented 2 weeks ago

Same issue as @jankrynauw any resolution anyone found?

Office.context.ui.messageParent("SAMPLE", { targetOrigin: "*" }); - This did not resolve issue either

image

For others I found no resolution to this issue on a mac and is a bug. Moved to use hidden layers/layout on same page vs popping new because context and callback simply does not work and does not register. Do not go down rabbit hole searching for resolution move to alternative forget pop use layers in same context hide/show.