GoHighLevel custom JavaScript snippets can add menu items, buttons, banners, and behavior the native platform doesn't offer—but most snippets you'll find online break because they don't account for GoHighLevel's dynamic, single-page interface. This guide covers how to write JS that actually holds up.
How GoHighLevel loads its UI (and why naive JS fails)
Before any code, it helps to know where the two injection points are and what they have in common. Agency-level JavaScript goes under Agency Settings → Company, in the Custom JavaScript field, wrapped in script tags, and it runs for every user in every sub-account of that agency. A marketplace app can ship custom JavaScript too, as plain JS in the app's Custom JS field, and that copy reaches every agency that installs the app once HighLevel has reviewed it. I write both kinds, and the engineering rules are identical; the marketplace route just adds a human reviewer and a save-time validator that enforce them.
The thing most GoHighLevel custom JavaScript snippets get wrong is the assumption that the page is a page. It isn't. HighLevel's app is a single-page application built on Vue: the browser loads one HTML shell, and from then on the sidebar, the header and every view are rendered by JavaScript. Moving between Dashboard, Conversations and Launchpad goes through the client-side router without a full reload, so your script runs exactly once, when the shell loads, and never again on its own.
Two consequences follow. First, elements appear asynchronously. When your code runs, document.querySelector("header.hl_header") often returns null because the header has not been mounted yet, and some areas, Launchpad among them, mount an empty root container first and fill in the real content later. Second, elements get replaced. When a route changes, Vue tears components down and builds new ones, and anything you appended inside them is discarded with the parent. A button that worked on load vanishes after the first click in the sidebar.
That explains the three failure modes I keep seeing in copied GoHighLevel custom JavaScript: a setTimeout of a few seconds that races the network and loses on slower connections, a setInterval that polls forever and happily inserts a second and third copy of the same button, and a listener attached to an element that no longer exists. The fix is not a longer delay. It is treating the page as a stream of changes and re-checking your work every time it changes. If all you need is restyling, custom CSS sidesteps this whole problem; the moment you need to add, move or wire up something, you need the patterns below.
Waiting for elements safely (the MutationObserver pattern)
MutationObserver is the browser's native way to be told when the DOM changes. You point it at a node, usually document.body, with childList and subtree enabled, and it calls you after every batch of insertions and removals. For a one-off wait, that gives you a helper that fires the moment an element exists, with a timeout so it never hangs around forever:
function whenReady(selector, callback, timeoutMs) {
var done = false;
var observer = null;
var timer = 0;
function finish(node) {
if (done) return;
done = true;
if (observer) observer.disconnect();
if (timer) clearTimeout(timer);
if (node) callback(node);
}
var existing = document.querySelector(selector);
if (existing) {
finish(existing);
return function () {};
}
observer = new MutationObserver(function () {
var node = document.querySelector(selector);
if (node) finish(node);
});
observer.observe(document.body, { childList: true, subtree: true });
timer = setTimeout(function () {
finish(null);
}, timeoutMs || 15000);
return function () {
finish(null);
};
}
whenReady("header.hl_header", function (header) {
header.setAttribute("data-acme-seen", "true");
});The details matter. It checks synchronously first, so it costs nothing when the element is already there. It disconnects itself as soon as it fires, so it does not keep watching. And it returns a cancel function, so whoever asked for the wait can withdraw it. Compared with setTimeout, it fires at the right moment on a fast connection and still works on a slow one. Compared with setInterval, it does no work while nothing is changing, which is most of the time.
A one-shot waiter is only half the answer, though, because of the replacement problem from the previous section. The header you waited for will be replaced on the next route change, and your button goes with it. What production GoHighLevel custom JavaScript snippets need is continuous reconciliation: one observer that stays attached, a short debounce so a burst of Vue renders triggers one pass instead of fifty, and a run() function that looks at the current page and makes sure everything that should be there is there. This is the frame every snippet in this article plugs into:
(function () {
"use strict";
if (window.AcmeGhl && typeof window.AcmeGhl.destroy === "function") {
window.AcmeGhl.destroy();
}
var PREFIX = "acme";
var STYLE_ID = PREFIX + "-style";
var APP_ORIGIN = "https://app.acme-example.com";
var DEBOUNCE_MS = 300;
var SVG_NS = "http://www.w3.org/2000/svg";
var state = { destroyed: false, paused: false, observer: null, timer: 0, cleanups: [] };
var features = [];
var cssRules = [];
function listen(target, type, handler, opts) {
target.addEventListener(type, handler, opts);
return function () {
target.removeEventListener(type, handler, opts);
};
}
function make(tag, className, text) {
var node = document.createElement(tag);
if (className) node.className = className;
if (text !== undefined) node.textContent = text;
return node;
}
function icon(pathData) {
var svg = document.createElementNS(SVG_NS, "svg");
svg.setAttribute("viewBox", "0 0 24 24");
svg.setAttribute("fill", "none");
svg.setAttribute("stroke", "currentColor");
svg.setAttribute("stroke-width", "2");
svg.setAttribute("aria-hidden", "true");
var path = document.createElementNS(SVG_NS, "path");
path.setAttribute("stroke-linecap", "round");
path.setAttribute("stroke-linejoin", "round");
path.setAttribute("d", pathData);
svg.appendChild(path);
return svg;
}
function removeNode(node) {
if (node && node.parentNode) node.parentNode.removeChild(node);
}
function locationFromUrl() {
var found = location.pathname.match(/\/location\/([A-Za-z0-9_-]+)/);
return found ? found[1] : "";
}
function ensureStyle() {
if (document.getElementById(STYLE_ID)) return;
var style = document.createElement("style");
style.setAttribute("id", STYLE_ID);
style.textContent = cssRules.join("");
document.head.appendChild(style);
}
function run() {
state.timer = 0;
if (state.destroyed) return;
var locationId = locationFromUrl();
if (locationId) ensureStyle();
for (var idx = 0; idx < features.length; idx++) {
if (locationId) features[idx].ensure(locationId);
else features[idx].remove();
}
}
function schedule() {
if (state.destroyed || state.paused || state.timer) return;
state.timer = setTimeout(run, DEBOUNCE_MS);
}
function pause() {
state.paused = true;
if (state.observer) state.observer.disconnect();
if (state.timer) clearTimeout(state.timer);
state.timer = 0;
}
function resume() {
if (state.destroyed || !state.paused) return;
state.paused = false;
if (state.observer) state.observer.observe(document.body, { childList: true, subtree: true });
schedule();
}
function destroy() {
if (state.destroyed) return;
state.destroyed = true;
if (state.observer) state.observer.disconnect();
state.observer = null;
if (state.timer) clearTimeout(state.timer);
state.timer = 0;
state.cleanups.forEach(function (off) {
off();
});
state.cleanups = [];
features.forEach(function (feature) {
feature.remove();
});
removeNode(document.getElementById(STYLE_ID));
if (window.AcmeGhl && window.AcmeGhl.destroy === destroy) window.AcmeGhl = undefined;
}
function start() {
if (state.destroyed || !document.body) return;
state.observer = new MutationObserver(schedule);
state.observer.observe(document.body, { childList: true, subtree: true });
state.cleanups.push(listen(window, "popstate", schedule));
state.cleanups.push(listen(window, "pagehide", pause));
state.cleanups.push(listen(window, "pageshow", resume));
schedule();
}
window.AcmeGhl = { destroy: destroy, refresh: schedule, version: "1.0.0" };
if (document.body) {
start();
} else {
var offReady = listen(document, "DOMContentLoaded", function () {
offReady();
start();
});
state.cleanups.push(offReady);
}
})();Walk through what it does. Every feature registers an ensure(locationId) and a remove(). run() reads the sub-account id from the /location/{id}/ segment of the URL, then calls each feature's ensure on sub-account pages and remove on agency-level pages, which have no such segment. schedule() collapses observer callbacks into a single run() 300 ms later. popstate covers back and forward navigation. pagehide and pageshow pause and resume the observer when the tab is backgrounded or brought back. And destroy() undoes everything, which is why it also runs at the very top: pasting a new version replaces the old copy instead of stacking a second one. Notice what is absent: no patched history.pushState, no setInterval, no reads of HighLevel's internal state. The observer already sees every re-render the router causes, so patching history buys nothing, and it is one of the things reviewers explicitly flag.
Snippet: add custom menu items in GoHighLevel
Before you add custom menu items in GoHighLevel with JavaScript, check whether the native option is enough. HighLevel has Custom Menu Links in the agency settings (and an API endpoint for creating them) that render in the sidebar, open a URL inside the app, and accept a location placeholder in that URL. For a plain link, that is the right tool, and it needs no maintenance. JavaScript earns its place when you need something native links cannot do: an item that opens your own modal, one that only appears on sub-accounts with a certain setting in your app, placement next to a specific GHL item, or an icon that matches the rest of the sidebar.
The snippet below finds an existing sidebar link as a reference point, copies its class list so the new item inherits GHL's own styling, and inserts a sibling right after it. It plugs into the frame from the previous section: paste it above the window.AcmeGhl = ... line.
var MENU_LABEL = "Reports Hub";
var MENU_ICON = "M3 3v18h18M7 14l4-4 4 4 5-6";
cssRules.push(
"." + PREFIX + "-menu-item{cursor:pointer;}" +
"." + PREFIX + "-menu-item svg{width:20px;height:20px;flex:none;}"
);
function menuReference() {
return document.querySelector("#sidebar-v2 a[href$=\"/dashboard\"]");
}
function ensureMenuItem(locationId) {
var reference = menuReference();
if (!reference) return;
var sig = locationId + "|" + MENU_LABEL;
var item = document.getElementById(PREFIX + "-menu-item");
if (item && item.parentNode === reference.parentNode && item.getAttribute("data-sig") === sig) return;
removeNode(item);
var classes = reference.className.replace(/\bactive\b/g, "").trim();
item = make("a", classes + " " + PREFIX + "-menu-item");
item.setAttribute("id", PREFIX + "-menu-item");
item.setAttribute("data-sig", sig);
item.setAttribute("href", APP_ORIGIN + "/reports?locationId=" + encodeURIComponent(locationId));
item.setAttribute("target", "_blank");
item.setAttribute("rel", "noopener");
item.appendChild(icon(MENU_ICON));
var labelRef = reference.querySelector("span");
item.appendChild(make("span", labelRef ? labelRef.className : "", MENU_LABEL));
reference.parentNode.insertBefore(item, reference.nextSibling);
}
function removeMenuItem() {
removeNode(document.getElementById(PREFIX + "-menu-item"));
}
features.push({ ensure: ensureMenuItem, remove: removeMenuItem });Three decisions in there are deliberate. The reference selector, #sidebar-v2 a[href$="/dashboard"], anchors on a container id and a URL suffix rather than on GHL's utility classes, which change between deployments; it was correct when I wrote this, and you should confirm it in DevTools before relying on it. The active class is stripped from the copied class list so the new item does not render as selected. And the data-sig attribute carries the location id and the label: when run() fires again and the item is still in place with the same signature, nothing happens, which is what stops the observer from reacting to its own insertions.
The click opens your app in a new tab with rel="noopener". If you would rather keep users inside GHL, replace the href, target and rel lines with a click listener that calls the openModal helper from the next section. For agencies that want navigation fully reorganised, with renamed items, sections hidden per client and a different order, the same frame scales to that, and the menu and navigation customization service covers what I build for agencies that would rather not maintain it themselves.
Snippet: inject a custom button
A header button that opens your app in a modal is the most requested of all GoHighLevel custom code examples, because it puts the app one click away on every screen. The target is the control strip on the right of the header, header.hl_header .hl_header--controls. Two elements match that selector in the current markup, so the snippet picks the one with the most children, which is the visible one. Other agency scripts often insert their own wrapper into the same strip, so the button goes in as the first child and never depends on its siblings.
var BUTTON_LABEL = "Open Acme";
var BUTTON_ICON = "M9 12h6m-6 4h6M7 3h7l5 5v11a2 2 0 01-2 2H7a2 2 0 01-2-2V5a2 2 0 012-2z";
var modalOff = null;
cssRules.push(
"." + PREFIX + "-navbtn{display:inline-flex;align-items:center;gap:6px;height:32px;margin-right:8px;padding:5px 12px;border:1px solid #155EEF;border-radius:6px;background:#155EEF;color:#fff;font:600 12px/18px Roboto,system-ui,sans-serif;cursor:pointer;white-space:nowrap;}" +
"." + PREFIX + "-navbtn:hover{filter:brightness(.92);}" +
"." + PREFIX + "-navbtn svg{width:16px;height:16px;}" +
"." + PREFIX + "-modal{position:fixed;inset:0;z-index:2147483000;display:flex;align-items:center;justify-content:center;padding:24px;background:rgba(16,24,40,.55);}" +
"." + PREFIX + "-modal-box{display:flex;flex-direction:column;width:min(960px,100%);height:min(88vh,900px);background:#fff;border-radius:12px;overflow:hidden;}" +
"." + PREFIX + "-modal-head{display:flex;align-items:center;justify-content:space-between;padding:12px 16px;border-bottom:1px solid #EAECF0;font:600 15px/22px Inter,system-ui,sans-serif;color:#101828;}" +
"." + PREFIX + "-modal-close{border:0;background:transparent;font-size:22px;line-height:1;color:#667085;cursor:pointer;}" +
"." + PREFIX + "-modal-box iframe{flex:1;width:100%;border:0;}"
);
function headerControls() {
var best = null;
var all = document.querySelectorAll("header.hl_header .hl_header--controls");
for (var idx = 0; idx < all.length; idx++) {
if (!best || all[idx].children.length > best.children.length) best = all[idx];
}
return best;
}
function closeModal() {
removeNode(document.getElementById(PREFIX + "-modal"));
if (modalOff) {
modalOff();
modalOff = null;
}
}
function openModal(title, url) {
closeModal();
var modal = make("div", PREFIX + "-modal");
modal.setAttribute("id", PREFIX + "-modal");
modal.setAttribute("role", "dialog");
modal.setAttribute("aria-modal", "true");
modal.setAttribute("aria-label", title);
var box = make("div", PREFIX + "-modal-box");
var head = make("div", PREFIX + "-modal-head");
var close = make("button", PREFIX + "-modal-close", "\u00d7");
close.setAttribute("type", "button");
close.setAttribute("aria-label", "Close");
close.addEventListener("click", closeModal);
head.appendChild(make("span", "", title));
head.appendChild(close);
var frame = document.createElement("iframe");
frame.setAttribute("src", url);
frame.setAttribute("title", title);
frame.setAttribute("allow", "clipboard-write");
frame.setAttribute("referrerpolicy", "strict-origin-when-cross-origin");
box.appendChild(head);
box.appendChild(frame);
modal.appendChild(box);
modal.addEventListener("click", function (event) {
if (event.target === modal) closeModal();
});
document.body.appendChild(modal);
modalOff = listen(document, "keydown", function (event) {
if (event.key === "Escape") closeModal();
}, true);
close.focus();
}
function ensureHeaderButton(locationId) {
var controls = headerControls();
if (!controls) return;
var sig = locationId + "|" + BUTTON_LABEL;
var button = document.getElementById(PREFIX + "-navbtn");
if (button && button.parentNode === controls && button.getAttribute("data-sig") === sig) return;
removeNode(button);
button = make("button", PREFIX + "-navbtn");
button.setAttribute("id", PREFIX + "-navbtn");
button.setAttribute("type", "button");
button.setAttribute("data-sig", sig);
button.appendChild(icon(BUTTON_ICON));
button.appendChild(make("span", "", BUTTON_LABEL));
button.addEventListener("click", function () {
openModal(BUTTON_LABEL, APP_ORIGIN + "/?locationId=" + encodeURIComponent(locationId));
});
controls.insertBefore(button, controls.firstChild);
}
function removeHeaderButton() {
removeNode(document.getElementById(PREFIX + "-navbtn"));
closeModal();
}
features.push({ ensure: ensureHeaderButton, remove: removeHeaderButton });The styling copies HighLevel's primary button (32 px tall, 6 px radius, #155EEF, Roboto 600 at 12 px), so it looks native without touching GHL's classes. The modal is built from createElement and textContent only, which matters for review: innerHTML gets flagged even for constant markup. The iframe loads your own domain with the location id in the query string and asks for clipboard-write only; request camera or microphone access only if the feature truly needs it, and say so in your listing. The Escape key listener is the one piece of state that lives outside the DOM, so it is kept as a remover in modalOff and cleared whenever the modal closes or the script is destroyed.
The same shape handles most header work: a custom button that opens a booking page, a support widget or a billing portal. Announcement bars are a close cousin, inserted above the header instead of inside it, and I build custom banners with exactly the same frame: a stable container, a signature attribute, and a remove function.
Avoiding conflicts and memory leaks
A GoHighLevel account can carry several scripts at once: the agency's own box, one or more marketplace apps, and sometimes an older copy nobody removed. Conflicts and leaks come from scripts that act as if they are alone. The frame above already applies the rules that prevent that, but they are worth stating, because they are also what HighLevel's reviewers look for:
- Namespace everything. Every id, class and the single global (
window.AcmeGhl) carries your prefix. Nothing else is attached towindow, and nothing of GHL's is modified in place; if you need to hide something, do it with a CSS rule on a stable container rather than inline styles on GHL's children, which Vue may replace at any moment. - Make every injection idempotent. The
data-sigcheck meansrun()changes nothing when the page is already correct. Without it, your own insertion triggers the observer, which triggers another insertion, and the page fills with duplicates or the tab pegs a CPU core. - Own every listener and timer.
listen()returns a remover and every remover goes intostate.cleanups; every timer id lives instate.destroy()can then put the page back exactly as it found it, and running it at the top of the script means a re-paste replaces instead of stacks. - Never patch globals or poll. No
history.pushStatewrappers, nosetInterval, no monkey-patchedfetch. The debounced observer pluspopstatesees everything the router does. - Read context from the URL only. Take the location id from
/location/{id}/and resolve everything else on your server. Reading HighLevel's internal Vue state for the agency id is fragile, reviewers dislike it, and the validator rejects the words involved. - Stay on one domain. The iframe, and any request for per-location settings, go to your own domain; if your API lives elsewhere, proxy it. Requests are read-only GETs with an abort timeout and a short in-memory memo, never polling and never uploads. The white-label CDN injection case study shows how I serve the script itself from the agency's own domain so clients only ever see one brand.
The marketplace adds a second layer of rules that bite even when you never meant to break them. Reviewers reject scripts that load jQuery, icon fonts or anything else from a CDN, and any use of innerHTML, insertAdjacentHTML, eval or string timers. The save-time validator is cruder: it rejects a script that contains the words storage, cookie, credentials, cache, session, persist, store or vue anywhere, including credentials: "omit" on a fetch or a variable called restoreTabs, and it treats any one- or two-character identifier, including e in a catch block or i in a loop, as obfuscation. That is why every name in the snippets above is three characters or longer, why ids are set through setAttribute, and why there are no comments: keep the explanation in your repository README and ship the file exactly as it was reviewed. I run every script through a scanner for these patterns before anyone pastes it, because a clean scan is the minimum bar, not proof of approval.
When snippets aren't enough
The GoHighLevel custom JavaScript snippets above are static: the label, the target and the placement are fixed in the file. In my experience, agency requests stop being static within a month. They want the item to show only on sub-accounts that have the feature enabled, the label to come from each client's settings, or Launchpad replaced with their own onboarding. At that point the script needs a backend keyed by location id, a same-origin proxy so the browser still talks to one domain, request de-duplication and a memo so a busy agency does not hammer your API, and a test routine against the live DOM for every HighLevel release. For a marketplace app, add the review submission, the disclosure text and a change log for every version.
That is the work I do: scripts engineered against the real DOM, scanned against HighLevel's rules before anyone pastes them, documented and kept in version control, and extended into a full marketplace app when the feature outgrows a script. If you have a snippet that broke, a feature that cannot get past review, or an idea for what your clients should see when they log in, have a look at the custom CSS and JavaScript service or send me the details, and I will tell you honestly whether it is a thirty-line script or something bigger.
Frequently asked questions
Where do I add custom JavaScript in GoHighLevel?
At agency level it goes under Agency Settings → Company in the Custom JavaScript field, wrapped in script tags, and it runs for every user in every sub-account of that agency. Marketplace apps have a separate Custom JS field that takes plain JavaScript and is reviewed by HighLevel before it reaches the agencies that install the app.
Why does my snippet work after a refresh but disappear when I navigate?
GoHighLevel is a single-page app, so navigation re-renders the header, sidebar or view without reloading the page, and anything you inserted is discarded with the old component. Your script ran once at load and was never told to run again. Use a MutationObserver with a debounced reconcile pass so the script re-checks the page after every change.
Can I load jQuery or another library from a CDN in GoHighLevel custom JS?
A script tag will technically load in an agency box, but it is a supply-chain risk inside every client account, and HighLevel's marketplace review rejects third-party scripts and stylesheets outright. Everything in this article uses plain DOM APIs, and icons are drawn as inline SVG with createElementNS, so there is nothing external to load.
My script does not use localStorage, so why did the portal say local storage and cookies access is prohibited?
The save-time validator matches words, not behaviour. Terms like storage, cookie, credentials, cache, session, persist, store and vue anywhere in the file trigger it, even inside a variable name or a fetch option. Rename them (memo instead of cache, reset instead of restore), drop credentials: "omit", and the same script will save.
Does agency-level custom JavaScript run on every sub-account?
Yes. The agency Custom JavaScript field applies to every user in every sub-account, and it also runs on agency-level pages. That is why the frame in this article checks for a /location/ segment in the URL and removes its UI on agency pages instead of assuming it always has a sub-account to work with.
Should I use JavaScript or the native Custom Menu Links to add a sidebar item?
Use the native Custom Menu Links whenever a plain link that opens a URL is enough; they need no maintenance and survive updates. Reach for JavaScript when the item has to open a modal, appear only on certain sub-accounts, sit in a specific position, or match GHL's icons and styling exactly.
