I'd like to call a given function if it exists. I've written:
var backgroundPage = window.chrome && chrome.extension &&
chrome.extension.getBackgroundPage ? chrome.extension.getBackgroundPage() : null;
I'm wondering if there's a better way to short-circuit all of those checks and only call chrome.extension.getBackgroundPage
if it exists?
If I do
typeof chrome.extension.getBackgroundPage === 'function'
I will still encounter errors if chrome or chrome.extension are undefined.
In many scenarios I would be able to use a utility function such as https://lodash.com/docs#get:
var getBackgroundPage = _.get(window, 'chrome.extension.getBackgroundPage');
but for my specific scenario I'm unable to use a utility library as the full code is serving as a loader for lodash.