Skip to content

Instantly share code, notes, and snippets.

@xaphod
Created October 23, 2020 14:58
Show Gist options
  • Save xaphod/1c49725cca452912c1c8c348489afbec to your computer and use it in GitHub Desktop.
Save xaphod/1c49725cca452912c1c8c348489afbec to your computer and use it in GitHub Desktop.
Conditionally load HelpScout Beacon v2 in a React site
import { useLayoutEffect, useState } from 'react';
import loadBeacon from './loadBeacon';
const BeaconLoader = () => {
const [didLoad, setDidLoad] = useState(false);
useLayoutEffect(() => {
if (!didLoad && myConditionForWantingTheBeaconToShow) {
setDidLoad(true);
loadBeacon({ displayName, email, helpscoutSignature }); // parameters are optional, see loadBeacon.js
}
}, [didLoad, myConditionForWantingTheBeaconToShow]);
return null;
};
export default BeaconLoader;
import BeaconLoader from './BeaconLoader';
...
ReactDOM.render(
(
<BrowserRouter>
<Router />
<BeaconLoader />
</BrowserRouter>
),
document.getElementById('root'),
);
...
// seems to work if used from useLayoutEffect
// Note: remove this from your index.html / HTML - this is the loader (verbatim/unchanged), you don't want to run it twice.
const loadBeacon = ({ displayName, email, helpscoutSignature }) => {
!(function (e, t, n) {
function a() {
var e = t.getElementsByTagName("script")[0],
n = t.createElement("script");
(n.type = "text/javascript"), (n.async = !0), (n.src = "https://beacon-v2.helpscout.net"), e.parentNode.insertBefore(n, e);
}
if (
((e.Beacon = n = function (t, n, a) {
e.Beacon.readyQueue.push({ method: t, options: n, data: a });
}),
(n.readyQueue = []),
"complete" === t.readyState)
)
return a();
e.attachEvent ? e.attachEvent("onload", a) : e.addEventListener("load", a, !1);
})(window, document, window.Beacon || function () {});
window.Beacon('init', 'your-init-code-here');
// Identifying is optional:
window.Beacon('identify', {
name: 'the-name',
email: 'the-email',
signature: 'your-signature-here',
});
};
export default loadBeacon;
@xaphod
Copy link
Author

xaphod commented Oct 23, 2020

The idea here was that sometimes you want to hide the Beacon, and other times you want to show it. For me, I wanted it only shown to users who are logged in, and only when secure (signature) is available.

Not pictured here: I call window.Beacon.destroy() on signout.

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