In developing a Microsoft Word Online add-in, my team needs to detect focus being gained/regained by the document (ETA: to trigger other functionality which depends on this knowledge). It appears that Microsoft has tightly locked down scriptability in this context--all window.on* functions are replaced by null, all error-handling code is deeply obfuscated, etc. Our efforts so far have been frustrated.
Simply setting window.onfocus to a new function causes the add-in to not load correctly, likely because it's triggering a code analyzer as unsafe, but hard to tell.
There is also nothing in the Microsoft Word Online JavaScript API which directly provides this functionality. Scripts can detect when the document selection has changed easily with a provided method, but that seems to be about it for documented functionality in this area. (Obviously simply sensing document changes will not work.)
What's the best approach to sensing document and/or window focus in this situation? Thank you.
The document.onvisibilitychange event can be used as a rough approximation of the required functionality.
document.onvisibilitychange = (ev) => {
if (document.visibilityState == "visible") {
// Handle pseudo-focus event
}
else {
// Handle pseudo-blur event
}
};
This may be combined as desired with with the Office Online API DocumentSelectionChanged event to refine further to sense when the cursor is placed within the Word document. (That is, fire focus-gained logic only when the Office DocumentSelectionChanged event is fired the first time after the browser document.onvisibilitychange event fired with document.visibilityState equal to "visible".)