Skip to content

Instantly share code, notes, and snippets.

@kendhia
Created March 29, 2023 13:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kendhia/caf287d51d9ff24ea2838b7b87989d84 to your computer and use it in GitHub Desktop.
Save kendhia/caf287d51d9ff24ea2838b7b87989d84 to your computer and use it in GitHub Desktop.
Intercom integration with nextjs, in typescript.
declare global {
interface Window {
Intercom?: any;
intercomSettings?: any;
attachEvent?: any;
}
}
import { useEffect } from 'react';
import { useRouter } from 'next/router';
export const APP_ID = process.env.INTERCOM_APP_ID;
// Loads Intercom with the snippet
// This must be run before boot, it initializes window.Intercom
export const load = () => {
(function () {
const w = window;
const ic = w.Intercom;
if (typeof ic === 'function') {
ic('reattach_activator');
ic('update', w.intercomSettings);
} else {
const d = document;
const i = function () {
// eslint-disable-next-line prefer-rest-params
i.c(arguments);
};
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
i.q = [];
i.c = function (args: any) {
i.q.push(args);
};
w.Intercom = i;
const l = function () {
const s = d.createElement('script');
s.type = 'text/javascript';
s.async = true;
s.src = 'https://widget.intercom.io/widget/' + APP_ID;
const x = d.getElementsByTagName('script')[0];
(x.parentNode as ParentNode).insertBefore(s, x);
};
if (document.readyState === 'complete') {
l();
} else if (w.attachEvent) {
w.attachEvent('onload', l);
} else {
w.addEventListener('load', l, false);
}
}
})();
};
// Initializes Intercom
export const boot = (options = {}) => {
window &&
window.Intercom &&
window.Intercom('boot', { app_id: APP_ID, ...options });
};
export const update = () => {
window && window.Intercom && window.Intercom('update');
};
export const shutdown = () => {
window && window.Intercom && window.Intercom('shutdown');
boot();
};
export function hide() {
window && window.Intercom && window && window.Intercom('hide');
}
export const IntercomProvider = ({ children }: { children: JSX.Element }) => {
const router = useRouter();
if (typeof window !== 'undefined') {
loadIntercom();
bootIntercom();
}
useEffect(() => {
const handleRouteChange = () => {
if (typeof window !== 'undefined') {
updateIntercom();
}
};
router.events.on('routeChangeStart', handleRouteChange);
// If the component is unmounted, unsubscribe
// from the event with the `off` method:
return () => {
router.events.off('routeChangeStart', handleRouteChange);
};
}, [router.events]);
return children;
};
@kendhia
Copy link
Author

kendhia commented Mar 29, 2023

For the JS version, you can have a look at this example.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment