|
| 1 | +import { useEffect } from 'react'; |
| 2 | + |
| 3 | +// Declare Intercom as a global function |
| 4 | +declare global { |
| 5 | + interface Window { |
| 6 | + Intercom: any; |
| 7 | + } |
| 8 | +} |
| 9 | + |
| 10 | +export function useIntercom(userName: string, userEmail: string) { |
| 11 | + useEffect(() => { |
| 12 | + // Check if we're in a browser environment |
| 13 | + if (typeof window === 'undefined' || typeof document === 'undefined') { |
| 14 | + console.warn('Intercom setup aborted: Not in a browser environment'); |
| 15 | + return; |
| 16 | + } |
| 17 | + |
| 18 | + // Intercom setup function |
| 19 | + const setupIntercom = () => { |
| 20 | + (function() { |
| 21 | + let w = window as any; |
| 22 | + let ic = w.Intercom; |
| 23 | + if (typeof ic === "function") { |
| 24 | + ic('reattach_activator'); |
| 25 | + ic('update', w.intercomSettings); |
| 26 | + } else { |
| 27 | + let d = document; |
| 28 | + let i = function () { |
| 29 | + (i as any).c(arguments); |
| 30 | + }; |
| 31 | + (i as any).q = []; |
| 32 | + (i as any).c = function(args: any) { |
| 33 | + (i as any).q.push(args); |
| 34 | + }; |
| 35 | + w.Intercom = i; |
| 36 | + let l = function () { |
| 37 | + let s = d.createElement('script'); |
| 38 | + s.type = 'text/javascript'; |
| 39 | + s.async = true; |
| 40 | + s.src = 'https://widget.intercom.io/widget/ok1wowgi'; |
| 41 | + let x = d.getElementsByTagName('script')[0]; |
| 42 | + let parent = x?.parentNode || document.body |
| 43 | + parent.insertBefore(s, x || null); |
| 44 | + }; |
| 45 | + if (document.readyState === 'complete') { |
| 46 | + l(); |
| 47 | + } else if (w.attachEvent) { |
| 48 | + w.attachEvent('onload', l); |
| 49 | + } else { |
| 50 | + w.addEventListener('load', l, false); |
| 51 | + } |
| 52 | + } |
| 53 | + })(); |
| 54 | + |
| 55 | + window.Intercom("boot", { |
| 56 | + api_base: "https://api-iam.intercom.io", |
| 57 | + app_id: "ok1wowgi", |
| 58 | + name: userName, |
| 59 | + email: userEmail, |
| 60 | + }); |
| 61 | + }; |
| 62 | + |
| 63 | + setupIntercom(); |
| 64 | + |
| 65 | + // Cleanup function |
| 66 | + return () => { |
| 67 | + if (window.Intercom) { |
| 68 | + window.Intercom('shutdown'); |
| 69 | + } |
| 70 | + }; |
| 71 | + }, [userName, userEmail]); // Re-run if userName or userEmail changes |
| 72 | +} |
0 commit comments