| 1 |
import { |
| 2 |
deviceId, |
| 3 |
hubspotBaseUrl, |
| 4 |
locale, |
| 5 |
portalId, |
| 6 |
leadinPluginVersion, |
| 7 |
} from '../constants/leadinConfig'; |
| 8 |
import { initApp } from './appUtils'; |
| 9 |
import { fetchAccessToken } from '../api/wordpressApiClient'; |
| 10 |
|
| 11 |
type CallbackFn = (...args: any[]) => void; |
| 12 |
|
| 13 |
export function initBackgroundApp(initFn: CallbackFn | CallbackFn[]) { |
| 14 |
function main() { |
| 15 |
if (Array.isArray(initFn)) { |
| 16 |
initFn.forEach(callback => callback()); |
| 17 |
} else { |
| 18 |
initFn(); |
| 19 |
} |
| 20 |
} |
| 21 |
initApp(main); |
| 22 |
} |
| 23 |
|
| 24 |
const getLeadinConfig = () => { |
| 25 |
return { |
| 26 |
leadinPluginVersion, |
| 27 |
}; |
| 28 |
}; |
| 29 |
|
| 30 |
export const getOrCreateBackgroundApp = (accessToken = '', expiresIn = 0) => { |
| 31 |
if ((window as any).LeadinBackgroundApp) { |
| 32 |
return (window as any).LeadinBackgroundApp; |
| 33 |
} |
| 34 |
const { IntegratedAppEmbedder, IntegratedAppOptions }: any = window; |
| 35 |
const options = new IntegratedAppOptions() |
| 36 |
.setLocale(locale) |
| 37 |
.setDeviceId(deviceId) |
| 38 |
.setLeadinConfig(getLeadinConfig()) |
| 39 |
.setAccessToken(accessToken, expiresIn); |
| 40 |
|
| 41 |
const embedder = new IntegratedAppEmbedder( |
| 42 |
'integrated-plugin-proxy', |
| 43 |
portalId, |
| 44 |
hubspotBaseUrl, |
| 45 |
() => {} |
| 46 |
).setOptions(options); |
| 47 |
|
| 48 |
embedder.attachTo(document.body, false); |
| 49 |
embedder.setTokenRenewalCallback(fetchAccessToken); |
| 50 |
embedder.postStartAppMessage(); // lets the app know all data has been passed to it |
| 51 |
|
| 52 |
(window as any).LeadinBackgroundApp = embedder; |
| 53 |
return (window as any).LeadinBackgroundApp; |
| 54 |
}; |
| 55 |
|