Skip to content

Commit

Permalink
feat: allow crumbs to be loaded on the server
Browse files Browse the repository at this point in the history
  • Loading branch information
robertlyall committed Nov 4, 2024
1 parent 996862b commit 719b89a
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 12 deletions.
2 changes: 1 addition & 1 deletion example.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import Crumbs from "./lib";
import Crumbs, { parseAccepted } from "./lib";

document.addEventListener("DOMContentLoaded", () => {
const editCookieButton = document.querySelector(".js-edit");
Expand Down
29 changes: 18 additions & 11 deletions lib/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,14 +3,6 @@ import { editScreen } from "./components/editScreen";
import { cookieBanner } from "./components/cookieBanner";
import { TYPES } from "./constants";

window.dataLayer = window.dataLayer || [];

window.gtag =
window.gtag ||
function () {
dataLayer.push(arguments);
};

/**
* Formats an array of types by adding a summary to each type.
* If a type does not have a summary, it uses the corresponding default consent type summary.
Expand Down Expand Up @@ -92,6 +84,18 @@ export default class Crumbs extends EventEmitter {
this.render();
}

gtag = (...params) => {
window.dataLayer = window.dataLayer || [];

window.gtag =
window.gtag ||
function () {
dataLayer.push(arguments);
};

window.gtag(...params);
};

outdated() {
return this.cookie.version < this.version;
}
Expand Down Expand Up @@ -135,7 +139,7 @@ export default class Crumbs extends EventEmitter {
const accepted = migration.call(this, this.cookie.value);

// The migration returned null rather than a collection of consent, let's clear the cookie
if (accepted === null || !Array.isArray(accepted)) {
if (accepted == null || !Array.isArray(accepted)) {
this.accepted = [];
this.clear();
return;
Expand All @@ -156,7 +160,7 @@ export default class Crumbs extends EventEmitter {
};

broadcast(type = "default") {
window.gtag(
this.gtag(
"consent",
type,
this.types.reduce(
Expand Down Expand Up @@ -532,7 +536,10 @@ export default class Crumbs extends EventEmitter {
...this.accepted,
].join("|")};domain=${this.domain}${expiry}; path=/;SameSite=None; Secure`;

this.cookie = value;
this.cookie = {
value,
version: this.version,
};
}

/**
Expand Down

0 comments on commit 719b89a

Please sign in to comment.