/
messenger.ts
89 lines (82 loc) · 1.97 KB
/
messenger.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
import { State } from '../types'
import waitForLoad from '../utils/waitForLoad'
const domain = 'https://connect.facebook.net'
declare global {
interface Window {
//eslint-disable-next-line @typescript-eslint/no-explicit-any
FB: any
fbAsyncInit: () => void
}
}
/* eslint-disable */
const loadScript = (locale: string): boolean => {
if (window.FB) return false
;(function loadFacebookSDK(d, s, id) {
// fetch customerchat.js
const fjs = d.getElementsByTagName(s)[0]
if (d.getElementById(id)) {
return
}
const js = d.createElement(s) as any
js.id = id
js.src = `${domain}/${locale}/sdk/xfbml.customerchat.js`
if (fjs) {
fjs.parentNode?.insertBefore(js, fjs)
} else {
d.body.appendChild(js)
}
})(window.document, 'script', 'facebook-jssdk')
return true
}
/* eslint-enable */
const load = ({
appID,
locale = 'en_US',
setState,
beforeInit = () => undefined,
onReady = () => undefined
}: {
appID?: string
locale?: string
setState: (state: State) => void
beforeInit?: () => void
onReady?: () => void
}): boolean => {
const loaded = loadScript(locale)
// Continue as long as messenger hasn’t already been initialised.
if (loaded) {
beforeInit()
window.fbAsyncInit = function() {
window.FB.init(
Object.assign(
{
cookie: true,
xfbml: true,
version: 'v6.0'
},
appID ? { appId: appID } : {}
)
)
window.FB.Event.subscribe('customerchat.load', () =>
// Allow messenger to complete loading before removing fake widget
setTimeout(() => {
setState('complete')
onReady()
}, 3000)
)
}
}
return loaded
}
const open = (): void => {
waitForLoad(
() => !!window.FB?.CustomerChat?.show,
// messenger is slow to show once it has loaded
() => setTimeout(() => window.FB.CustomerChat.show(true), 2000)
)
}
export default {
domain,
load,
open
}