How to correctly check the host: Office, Office on

2019-07-31 01:52发布

问题:

I need to detect whether a user has hit the URL of my add-in from a browser, outside of Office and Office online. (I've seen questions here about detecting whether it is Excel, or Excel online, but not neither of them.)

I've looked at the utility functions OfficeHelpers.Utilities.host and OfficeHelpers.Utilities.isAddin but the code notes say these will only work after Office.initialize is called. If the URL has been navigated to from outside of an Office client then this won't be the case (?).

So I think I need to perform the same check as whatever is being done when you get the warning: Warning in Google Chrome ...to make sure that the Office.initialize will not be run, not that it hasn't run yet.

A simple use of this, would be to direct users to a page that displays explains they cannot access this without loading it as an add-in, and instructions on how to load the add-in etc.

The actual result I am trying to get is to handle both cases as:

From within an Office client: "GetData" will return some values and write them to a document. If accessed from a browser: "GetData" will return some values and redirect to a View to display these.

回答1:

There is no great solution for this at the moment, though I agree that there is an opportunity here to expose an "Office.ready" to provide a definitive sign that Office.js loaded one way or another -- and that the host and platform are now stably determined (including determined to be stably "web" and null).

For Script Lab, we use the approach of waiting on Office.js for three seconds, and then giving up and displaying a disambuguation set of buttons to the user, asking them to choose the host. We could probably safely assume "web" at that point, but in our case we want to provide a disambiguation experience in any case, so users can choose whether to run web snippets or view host-specific ones where they would need a host choice anyway.

If you're curious to see how it is done, see the "initialize" function in https://github.com/OfficeDev/script-lab/blob/eeb4ba89a7a570cf1bb035fdd740ec7dcfb92822/src/client/app/helpers/environment.ts



标签: office-js