About a year ago we started to use Intercom at Appcelerator to improve our support and communication with our users. You might have seen the red “bubble” on the bottom right of our properties:
The variable we need ..
I recently needed to detect if the Intercom Messenger was enabled for a user on the Developer Portal – Help page. Once it has booted, the window will have a intercomSettings
variable with handy properties like is_intercom_bubble_enabled
.
.. but doesn’t exist yet
However, due to the way our unified top navigation handles the injection of the Intercom script after the scripts on the page itself have already initialised, I needed a way to wait for Intercom Messenger to boot.
And how to wait until it does
Intercom’s JavaScript API does not provide a way to do this, but I was able to do this using Object.defineProperty(). By defining a setter and getter for this property I can simply wait for the Intercom script to set the variable, which will call the setter function. And voila, there you are:
You could easily apply the same trick to other libraries that define global variables and you need to wait for. Perhaps wrap it in a tiny library so that you can do something like:
1 2 3 |
whenDefined(window, 'intercomSettings', function() { // do something }); |
For a long time I was hoping on the adoption of Object.observe() to handle situations like this, but this is actually a pretty good alternative.
Great article, really useful! would have saved me loads of time in the past rather than using setIntervals! So I’ve created this into a bower component for people to use https://github.com/OwenMelbz/whendefined
Excellent Owen!