@owlmeans/web-gtm 0.1.18-rc.10
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +15 -0
- package/agent-meta/manifest.json +16 -0
- package/agent-meta/skills/web-gtm/SKILL.md +96 -0
- package/build/index.d.ts +30 -0
- package/build/index.d.ts.map +1 -0
- package/build/index.js +52 -0
- package/build/index.js.map +1 -0
- package/package.json +36 -0
- package/src/index.ts +65 -0
- package/tests/head.spec.ts +65 -0
- package/tsconfig.json +11 -0
package/README.md
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
<!-- owlmeans:agent-guidance:start -->
|
|
2
|
+
## Agent guidance
|
|
3
|
+
|
|
4
|
+
This package ships embedded agent skills under `agent-meta/`. After installing your
|
|
5
|
+
`@owlmeans/*` packages, run the OwlMeans agent-skills installer to place them into
|
|
6
|
+
your project's skill store (`.agents/skills/`):
|
|
7
|
+
|
|
8
|
+
```sh
|
|
9
|
+
npx @owlmeans/agent-skills@^0.1.18-rc.16
|
|
10
|
+
```
|
|
11
|
+
|
|
12
|
+
The embedded files are version-matched to this package release. Do not edit them
|
|
13
|
+
directly — they are regenerated on each publish. To contribute guidance edits,
|
|
14
|
+
open a PR against the source monorepo.
|
|
15
|
+
<!-- owlmeans:agent-guidance:end -->
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
{
|
|
2
|
+
"schemaVersion": 2,
|
|
3
|
+
"package": "@owlmeans/web-gtm",
|
|
4
|
+
"version": "0.1.18-rc.10",
|
|
5
|
+
"generatedAt": "2026-09-12T12:33:32.485Z",
|
|
6
|
+
"canonicalRepo": "https://github.com/owlmeans/common",
|
|
7
|
+
"entries": [
|
|
8
|
+
{
|
|
9
|
+
"kind": "skill",
|
|
10
|
+
"name": "web-gtm",
|
|
11
|
+
"category": "package-specific",
|
|
12
|
+
"file": "skills/web-gtm/SKILL.md",
|
|
13
|
+
"canonicalPath": ".agents/skills/web-gtm/SKILL.md"
|
|
14
|
+
}
|
|
15
|
+
]
|
|
16
|
+
}
|
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
---
|
|
2
|
+
name: web-gtm
|
|
3
|
+
description: How to use @owlmeans/web-gtm — the Google Tag Manager head snippet that declares Consent Mode defaults before the container loads, the noscript frame, and the script-side loader for a host that cannot edit its own HTML. Auto-invoked when adding a tag manager to a page, importing gtmHeadScript, gtmNoscriptFrame or loadGtm, or debugging why a tag ignores a stored consent decision.
|
|
4
|
+
user-invocable: false
|
|
5
|
+
---
|
|
6
|
+
<!-- AUTO-GENERATED — do not edit. Regenerate via sync-agent-meta. -->
|
|
7
|
+
|
|
8
|
+
# @owlmeans/web-gtm
|
|
9
|
+
|
|
10
|
+
**Layer:** Web
|
|
11
|
+
**Install:** `"@owlmeans/web-gtm": "^0.1.18-rc.10"` in `dependencies`
|
|
12
|
+
|
|
13
|
+
The tag-manager half of the consent set. It emits **strings**, not components, and it holds no
|
|
14
|
+
state — the decision lives in `@owlmeans/consent`, which this package reads through
|
|
15
|
+
`consentBootstrapScript` and `consentStore`.
|
|
16
|
+
|
|
17
|
+
## The one idea: order
|
|
18
|
+
|
|
19
|
+
Google Tag Manager decides what a tag may do from the consent state present **when the container
|
|
20
|
+
loads**. A React bundle cannot get there first: by the time an island mounts, `gtm.js` has been
|
|
21
|
+
running for hundreds of milliseconds and has already decided. A site whose defaults arrive after
|
|
22
|
+
the container is not configured differently — it is *unconfigured for the window that matters*, and
|
|
23
|
+
nothing in the page reports it.
|
|
24
|
+
|
|
25
|
+
So `gtmHeadScript` emits the consent bootstrap and then the container, in that order, as one
|
|
26
|
+
inline script. Everything else in this package exists to serve that.
|
|
27
|
+
|
|
28
|
+
## Key Exports
|
|
29
|
+
|
|
30
|
+
| Export | Description |
|
|
31
|
+
|--------|-------------|
|
|
32
|
+
| `gtmHeadScript(opts)` | The inline `<head>` snippet: consent defaults, stored decision, then the container |
|
|
33
|
+
| `gtmNoscriptFrame(opts)` | The hidden `<noscript>` iframe, for the top of `<body>` |
|
|
34
|
+
| `loadGtm(opts)` | Script-side container load, for a host that cannot emit into its own head |
|
|
35
|
+
| `GtmOptions` | `ConsentOptions` plus `id` (e.g. `GTM-XXXXXXX`) and optional `dataLayerName` |
|
|
36
|
+
|
|
37
|
+
## Stamping it
|
|
38
|
+
|
|
39
|
+
```typescript
|
|
40
|
+
import { gtmHeadScript, gtmNoscriptFrame } from '@owlmeans/web-gtm'
|
|
41
|
+
|
|
42
|
+
const opts = { id: 'GTM-XXXXXXX' }
|
|
43
|
+
const head = gtmHeadScript(opts) // inline <script> content for <head>, first
|
|
44
|
+
const frame = gtmNoscriptFrame(opts) // <noscript> content for the top of <body>
|
|
45
|
+
```
|
|
46
|
+
|
|
47
|
+
The snippet is stamped **from HTML**, never from the application bundle. How each surface does it:
|
|
48
|
+
|
|
49
|
+
- a Vite app — a `transformIndexHtml` plugin substituting the two markers, so the snippet cannot
|
|
50
|
+
drift from the package;
|
|
51
|
+
- an Astro site — `owlHeadScripts()` from `@owlmeans/astro`, `set:html` in the base layout.
|
|
52
|
+
|
|
53
|
+
A surface that runs no container of its own stamps only `consentBootstrapScript()` from
|
|
54
|
+
`@owlmeans/consent` — that is the case for the bundler-generated `index.html` of a generated
|
|
55
|
+
application, which carries the consent bootstrap and no tag manager. The bootstrap and this
|
|
56
|
+
snippet are separate stampings: adding a container means adding `gtmHeadScript` /
|
|
57
|
+
`gtmNoscriptFrame` beside it.
|
|
58
|
+
|
|
59
|
+
`gtmHeadScript` also **reads the stored decision** and pushes `consent/update` before the
|
|
60
|
+
container, so a returning visitor's tags are not denied for the first paint of every page. That
|
|
61
|
+
read is why the same `ConsentOptions` (categories, `storageKey`) must be passed here and to the
|
|
62
|
+
dialog: two different category sets in one page mean the snippet and the component disagree about
|
|
63
|
+
what was asked.
|
|
64
|
+
|
|
65
|
+
## Gotchas
|
|
66
|
+
|
|
67
|
+
- **The container id and queue name are injected as data, never interpolated raw.** Both come from
|
|
68
|
+
configuration, and configuration reaches these functions as a string. `gtmHeadScript` JSON-encodes
|
|
69
|
+
them, so a quote inside an id is escaped rather than closing the literal and turning the rest into
|
|
70
|
+
executable script; `gtmNoscriptFrame` URL-encodes the id so it cannot break out of the attribute.
|
|
71
|
+
Never build either string by hand.
|
|
72
|
+
- **`dataLayerName` is for a page running more than one container.** It is passed through to the
|
|
73
|
+
container the way Google's own snippet does (`&l=` when it is not `dataLayer`); leave it unset
|
|
74
|
+
otherwise, or tags looking at the default queue see nothing.
|
|
75
|
+
- **`loadGtm` is the fallback, not the default.** It is for a single-page app whose HTML is not
|
|
76
|
+
yours to edit. It still pushes the defaults first (through `consentStore.init`) and refuses to
|
|
77
|
+
load a second time — it marks its own `<script>` element with an id derived from the container —
|
|
78
|
+
but it runs after the bundle, which is exactly the window the head snippet closes. Prefer the
|
|
79
|
+
head snippet wherever the document can be edited.
|
|
80
|
+
- **A second `consent/default` after a tag has loaded can WIDEN what was already narrowed**, so the
|
|
81
|
+
bootstrap is idempotent through a window flag. A page may therefore carry the call twice — once
|
|
82
|
+
inline, once from the bundle that mounts the dialog — without harm. Do not defeat the flag.
|
|
83
|
+
- `loadGtm` returns immediately when there is no `document`, so it is safe to call from code that
|
|
84
|
+
also runs during server rendering.
|
|
85
|
+
|
|
86
|
+
## Depends On
|
|
87
|
+
|
|
88
|
+
- `@owlmeans/consent` — `consentBootstrapScript`, `consentStore`, `ConsentOptions`, the category
|
|
89
|
+
model and the Consent Mode signal mapping
|
|
90
|
+
|
|
91
|
+
## Related
|
|
92
|
+
|
|
93
|
+
- `consent` — categories, the storage record and its migration, Consent Mode v2 signalling, and the
|
|
94
|
+
ordering rule this package implements
|
|
95
|
+
- `web-consent` — the dialog and the cookie-policy page that produce the decision
|
|
96
|
+
- `astro` — `owlHeadScripts()`, which composes both strings for an Astro layout
|
package/build/index.d.ts
ADDED
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
import type { ConsentOptions } from '@owlmeans/consent';
|
|
2
|
+
export interface GtmOptions extends ConsentOptions {
|
|
3
|
+
/** Container id, e.g. `GTM-XXXXXXX`. */
|
|
4
|
+
id: string;
|
|
5
|
+
/** The queue name, when a page runs more than one container. */
|
|
6
|
+
dataLayerName?: string;
|
|
7
|
+
}
|
|
8
|
+
/**
|
|
9
|
+
* The inline `<head>` snippet, consent first and the container second.
|
|
10
|
+
*
|
|
11
|
+
* The ORDER is the whole point of this package. Google Tag Manager decides what a tag may do from
|
|
12
|
+
* the consent state present when the container loads, and a React bundle cannot get there first —
|
|
13
|
+
* by the time an island mounts, the container has been running for hundreds of milliseconds. A
|
|
14
|
+
* site whose defaults arrive after `gtm.js` is not configured differently; it is unconfigured for
|
|
15
|
+
* the window that matters, and nothing in the page reports it.
|
|
16
|
+
*
|
|
17
|
+
* Emit this into the document head, above everything else, as an inline script.
|
|
18
|
+
*/
|
|
19
|
+
export declare const gtmHeadScript: (opts: GtmOptions) => string;
|
|
20
|
+
/** The `<noscript>` iframe, for the body. */
|
|
21
|
+
export declare const gtmNoscriptFrame: (opts: GtmOptions) => string;
|
|
22
|
+
/**
|
|
23
|
+
* Load the container from script, for a host that cannot emit into its own head.
|
|
24
|
+
*
|
|
25
|
+
* The head snippet is strictly better and should be preferred; this exists for a single-page app
|
|
26
|
+
* whose HTML is not ours to edit. It still pushes the defaults first, and it still refuses to load
|
|
27
|
+
* a second time.
|
|
28
|
+
*/
|
|
29
|
+
export declare const loadGtm: (opts: GtmOptions) => void;
|
|
30
|
+
//# sourceMappingURL=index.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,mBAAmB,CAAA;AAEvD,MAAM,WAAW,UAAW,SAAQ,cAAc;IAChD,wCAAwC;IACxC,EAAE,EAAE,MAAM,CAAA;IACV,gEAAgE;IAChE,aAAa,CAAC,EAAE,MAAM,CAAA;CACvB;AAED;;;;;;;;;;GAUG;AACH,eAAO,MAAM,aAAa,SAAU,UAAU,KAAG,MAWhD,CAAA;AAED,6CAA6C;AAC7C,eAAO,MAAM,gBAAgB,SAAU,UAAU,KAAG,MAEsB,CAAA;AAE1E;;;;;;GAMG;AACH,eAAO,MAAM,OAAO,SAAU,UAAU,KAAG,IAkB1C,CAAA"}
|
package/build/index.js
ADDED
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
import { consentBootstrapScript, consentStore } from '@owlmeans/consent';
|
|
2
|
+
/**
|
|
3
|
+
* The inline `<head>` snippet, consent first and the container second.
|
|
4
|
+
*
|
|
5
|
+
* The ORDER is the whole point of this package. Google Tag Manager decides what a tag may do from
|
|
6
|
+
* the consent state present when the container loads, and a React bundle cannot get there first —
|
|
7
|
+
* by the time an island mounts, the container has been running for hundreds of milliseconds. A
|
|
8
|
+
* site whose defaults arrive after `gtm.js` is not configured differently; it is unconfigured for
|
|
9
|
+
* the window that matters, and nothing in the page reports it.
|
|
10
|
+
*
|
|
11
|
+
* Emit this into the document head, above everything else, as an inline script.
|
|
12
|
+
*/
|
|
13
|
+
export const gtmHeadScript = (opts) => {
|
|
14
|
+
const layer = opts.dataLayerName ?? 'dataLayer';
|
|
15
|
+
return `${consentBootstrapScript(opts)};` +
|
|
16
|
+
`(function(w,d,s,l,i){w[l]=w[l]||[];` +
|
|
17
|
+
`w[l].push({'gtm.start':new Date().getTime(),event:'gtm.js'});` +
|
|
18
|
+
`var f=d.getElementsByTagName(s)[0],j=d.createElement(s),` +
|
|
19
|
+
`dl=l!='dataLayer'?'&l='+l:'';j.async=true;` +
|
|
20
|
+
`j.src='https://www.googletagmanager.com/gtm.js?id='+i+dl;` +
|
|
21
|
+
`f.parentNode.insertBefore(j,f)})` +
|
|
22
|
+
`(window,document,'script',${JSON.stringify(layer)},${JSON.stringify(opts.id)})`;
|
|
23
|
+
};
|
|
24
|
+
/** The `<noscript>` iframe, for the body. */
|
|
25
|
+
export const gtmNoscriptFrame = (opts) => `<iframe src="https://www.googletagmanager.com/ns.html?id=${encodeURIComponent(opts.id)}"` +
|
|
26
|
+
` height="0" width="0" style="display:none;visibility:hidden"></iframe>`;
|
|
27
|
+
/**
|
|
28
|
+
* Load the container from script, for a host that cannot emit into its own head.
|
|
29
|
+
*
|
|
30
|
+
* The head snippet is strictly better and should be preferred; this exists for a single-page app
|
|
31
|
+
* whose HTML is not ours to edit. It still pushes the defaults first, and it still refuses to load
|
|
32
|
+
* a second time.
|
|
33
|
+
*/
|
|
34
|
+
export const loadGtm = (opts) => {
|
|
35
|
+
if (typeof document === 'undefined') {
|
|
36
|
+
return;
|
|
37
|
+
}
|
|
38
|
+
const marker = `owl-gtm-${opts.id}`;
|
|
39
|
+
if (document.getElementById(marker) != null) {
|
|
40
|
+
return;
|
|
41
|
+
}
|
|
42
|
+
// Defaults before the container, every time — the same rule the head snippet exists to keep.
|
|
43
|
+
consentStore.init(opts);
|
|
44
|
+
const layer = opts.dataLayerName ?? 'dataLayer';
|
|
45
|
+
const script = document.createElement('script');
|
|
46
|
+
script.id = marker;
|
|
47
|
+
script.async = true;
|
|
48
|
+
script.src = `https://www.googletagmanager.com/gtm.js?id=${encodeURIComponent(opts.id)}`
|
|
49
|
+
+ (layer !== 'dataLayer' ? `&l=${encodeURIComponent(layer)}` : '');
|
|
50
|
+
document.head.appendChild(script);
|
|
51
|
+
};
|
|
52
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,sBAAsB,EAAE,YAAY,EAAE,MAAM,mBAAmB,CAAA;AAUxE;;;;;;;;;;GAUG;AACH,MAAM,CAAC,MAAM,aAAa,GAAG,CAAC,IAAgB,EAAU,EAAE;IACxD,MAAM,KAAK,GAAG,IAAI,CAAC,aAAa,IAAI,WAAW,CAAA;IAE/C,OAAO,GAAG,sBAAsB,CAAC,IAAI,CAAC,GAAG;QACvC,qCAAqC;QACrC,+DAA+D;QAC/D,0DAA0D;QAC1D,4CAA4C;QAC5C,2DAA2D;QAC3D,kCAAkC;QAClC,6BAA6B,IAAI,CAAC,SAAS,CAAC,KAAK,CAAC,IAAI,IAAI,CAAC,SAAS,CAAC,IAAI,CAAC,EAAE,CAAC,GAAG,CAAA;AACpF,CAAC,CAAA;AAED,6CAA6C;AAC7C,MAAM,CAAC,MAAM,gBAAgB,GAAG,CAAC,IAAgB,EAAU,EAAE,CAC3D,4DAA4D,kBAAkB,CAAC,IAAI,CAAC,EAAE,CAAC,GAAG;IAC1F,wEAAwE,CAAA;AAE1E;;;;;;GAMG;AACH,MAAM,CAAC,MAAM,OAAO,GAAG,CAAC,IAAgB,EAAQ,EAAE;IAChD,IAAI,OAAO,QAAQ,KAAK,WAAW,EAAE,CAAC;QACpC,OAAM;IACR,CAAC;IACD,MAAM,MAAM,GAAG,WAAW,IAAI,CAAC,EAAE,EAAE,CAAA;IACnC,IAAI,QAAQ,CAAC,cAAc,CAAC,MAAM,CAAC,IAAI,IAAI,EAAE,CAAC;QAC5C,OAAM;IACR,CAAC;IACD,6FAA6F;IAC7F,YAAY,CAAC,IAAI,CAAC,IAAI,CAAC,CAAA;IAEvB,MAAM,KAAK,GAAG,IAAI,CAAC,aAAa,IAAI,WAAW,CAAA;IAC/C,MAAM,MAAM,GAAG,QAAQ,CAAC,aAAa,CAAC,QAAQ,CAAC,CAAA;IAC/C,MAAM,CAAC,EAAE,GAAG,MAAM,CAAA;IAClB,MAAM,CAAC,KAAK,GAAG,IAAI,CAAA;IACnB,MAAM,CAAC,GAAG,GAAG,8CAA8C,kBAAkB,CAAC,IAAI,CAAC,EAAE,CAAC,EAAE;UACpF,CAAC,KAAK,KAAK,WAAW,CAAC,CAAC,CAAC,MAAM,kBAAkB,CAAC,KAAK,CAAC,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC,CAAA;IACpE,QAAQ,CAAC,IAAI,CAAC,WAAW,CAAC,MAAM,CAAC,CAAA;AACnC,CAAC,CAAA"}
|
package/package.json
ADDED
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@owlmeans/web-gtm",
|
|
3
|
+
"version": "0.1.18-rc.10",
|
|
4
|
+
"license": "MIT",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"scripts": {
|
|
7
|
+
"build": "tsc -b",
|
|
8
|
+
"dev": "sleep 2 && nodemon -e ts,json --watch src --exec \"tsc -p ./tsconfig.json\"",
|
|
9
|
+
"watch": "tsc -b -w --preserveWatchOutput --pretty",
|
|
10
|
+
"test": "bun test ./tests"
|
|
11
|
+
},
|
|
12
|
+
"main": "build/index.js",
|
|
13
|
+
"module": "build/index.js",
|
|
14
|
+
"types": "build/index.d.ts",
|
|
15
|
+
"exports": {
|
|
16
|
+
".": {
|
|
17
|
+
"import": "./build/index.js",
|
|
18
|
+
"require": "./build/index.js",
|
|
19
|
+
"default": "./build/index.js",
|
|
20
|
+
"module": "./build/index.js",
|
|
21
|
+
"types": "./build/index.d.ts"
|
|
22
|
+
}
|
|
23
|
+
},
|
|
24
|
+
"dependencies": {
|
|
25
|
+
"@owlmeans/consent": "^0.1.18-rc.4"
|
|
26
|
+
},
|
|
27
|
+
"devDependencies": {
|
|
28
|
+
"@owlmeans/dep-config": "workspace:*",
|
|
29
|
+
"@types/bun": "^1.4.0",
|
|
30
|
+
"nodemon": "^3.1.14",
|
|
31
|
+
"typescript": "^7.0.2"
|
|
32
|
+
},
|
|
33
|
+
"publishConfig": {
|
|
34
|
+
"access": "public"
|
|
35
|
+
}
|
|
36
|
+
}
|
package/src/index.ts
ADDED
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
import { consentBootstrapScript, consentStore } from '@owlmeans/consent'
|
|
2
|
+
import type { ConsentOptions } from '@owlmeans/consent'
|
|
3
|
+
|
|
4
|
+
export interface GtmOptions extends ConsentOptions {
|
|
5
|
+
/** Container id, e.g. `GTM-XXXXXXX`. */
|
|
6
|
+
id: string
|
|
7
|
+
/** The queue name, when a page runs more than one container. */
|
|
8
|
+
dataLayerName?: string
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
/**
|
|
12
|
+
* The inline `<head>` snippet, consent first and the container second.
|
|
13
|
+
*
|
|
14
|
+
* The ORDER is the whole point of this package. Google Tag Manager decides what a tag may do from
|
|
15
|
+
* the consent state present when the container loads, and a React bundle cannot get there first —
|
|
16
|
+
* by the time an island mounts, the container has been running for hundreds of milliseconds. A
|
|
17
|
+
* site whose defaults arrive after `gtm.js` is not configured differently; it is unconfigured for
|
|
18
|
+
* the window that matters, and nothing in the page reports it.
|
|
19
|
+
*
|
|
20
|
+
* Emit this into the document head, above everything else, as an inline script.
|
|
21
|
+
*/
|
|
22
|
+
export const gtmHeadScript = (opts: GtmOptions): string => {
|
|
23
|
+
const layer = opts.dataLayerName ?? 'dataLayer'
|
|
24
|
+
|
|
25
|
+
return `${consentBootstrapScript(opts)};` +
|
|
26
|
+
`(function(w,d,s,l,i){w[l]=w[l]||[];` +
|
|
27
|
+
`w[l].push({'gtm.start':new Date().getTime(),event:'gtm.js'});` +
|
|
28
|
+
`var f=d.getElementsByTagName(s)[0],j=d.createElement(s),` +
|
|
29
|
+
`dl=l!='dataLayer'?'&l='+l:'';j.async=true;` +
|
|
30
|
+
`j.src='https://www.googletagmanager.com/gtm.js?id='+i+dl;` +
|
|
31
|
+
`f.parentNode.insertBefore(j,f)})` +
|
|
32
|
+
`(window,document,'script',${JSON.stringify(layer)},${JSON.stringify(opts.id)})`
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/** The `<noscript>` iframe, for the body. */
|
|
36
|
+
export const gtmNoscriptFrame = (opts: GtmOptions): string =>
|
|
37
|
+
`<iframe src="https://www.googletagmanager.com/ns.html?id=${encodeURIComponent(opts.id)}"` +
|
|
38
|
+
` height="0" width="0" style="display:none;visibility:hidden"></iframe>`
|
|
39
|
+
|
|
40
|
+
/**
|
|
41
|
+
* Load the container from script, for a host that cannot emit into its own head.
|
|
42
|
+
*
|
|
43
|
+
* The head snippet is strictly better and should be preferred; this exists for a single-page app
|
|
44
|
+
* whose HTML is not ours to edit. It still pushes the defaults first, and it still refuses to load
|
|
45
|
+
* a second time.
|
|
46
|
+
*/
|
|
47
|
+
export const loadGtm = (opts: GtmOptions): void => {
|
|
48
|
+
if (typeof document === 'undefined') {
|
|
49
|
+
return
|
|
50
|
+
}
|
|
51
|
+
const marker = `owl-gtm-${opts.id}`
|
|
52
|
+
if (document.getElementById(marker) != null) {
|
|
53
|
+
return
|
|
54
|
+
}
|
|
55
|
+
// Defaults before the container, every time — the same rule the head snippet exists to keep.
|
|
56
|
+
consentStore.init(opts)
|
|
57
|
+
|
|
58
|
+
const layer = opts.dataLayerName ?? 'dataLayer'
|
|
59
|
+
const script = document.createElement('script')
|
|
60
|
+
script.id = marker
|
|
61
|
+
script.async = true
|
|
62
|
+
script.src = `https://www.googletagmanager.com/gtm.js?id=${encodeURIComponent(opts.id)}`
|
|
63
|
+
+ (layer !== 'dataLayer' ? `&l=${encodeURIComponent(layer)}` : '')
|
|
64
|
+
document.head.appendChild(script)
|
|
65
|
+
}
|
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
import { describe, expect, test } from 'bun:test'
|
|
2
|
+
import { CONSENT_KEY } from '@owlmeans/consent'
|
|
3
|
+
import { gtmHeadScript, gtmNoscriptFrame } from '../src/index.js'
|
|
4
|
+
|
|
5
|
+
const ID = 'GTM-TESTID1'
|
|
6
|
+
|
|
7
|
+
describe('@owlmeans/web-gtm — the head snippet', () => {
|
|
8
|
+
test('the consent defaults are declared BEFORE the container is requested', async () => {
|
|
9
|
+
// The entire reason this package exists. Consent Mode decides what a tag may do from the state
|
|
10
|
+
// present when the container loads, so a `consent/default` that arrives after `gtm.js` leaves
|
|
11
|
+
// the page unconfigured for the window that matters — and nothing reports it. Asserted on
|
|
12
|
+
// offsets rather than on presence, because both strings are always present and only the order
|
|
13
|
+
// has ever been wrong.
|
|
14
|
+
const script = gtmHeadScript({ id: ID })
|
|
15
|
+
|
|
16
|
+
const defaults = script.indexOf("'consent','default'")
|
|
17
|
+
const container = script.indexOf('gtm.js')
|
|
18
|
+
|
|
19
|
+
expect(defaults).toBeGreaterThanOrEqual(0)
|
|
20
|
+
expect(container).toBeGreaterThanOrEqual(0)
|
|
21
|
+
expect(defaults).toBeLessThan(container)
|
|
22
|
+
})
|
|
23
|
+
|
|
24
|
+
test('it reads a stored decision, so a returning visitor is not treated as denied', async () => {
|
|
25
|
+
const script = gtmHeadScript({ id: ID })
|
|
26
|
+
|
|
27
|
+
expect(script).toContain(JSON.stringify(CONSENT_KEY))
|
|
28
|
+
expect(script).toContain("'consent','update'")
|
|
29
|
+
// And the read happens before the container too — a decision applied afterwards is a decision
|
|
30
|
+
// the first tag never saw.
|
|
31
|
+
expect(script.indexOf("'consent','update'")).toBeLessThan(script.indexOf('gtm.js'))
|
|
32
|
+
})
|
|
33
|
+
|
|
34
|
+
test('the container id and queue name are injected as data, never interpolated raw', async () => {
|
|
35
|
+
// These come from configuration, and configuration reaches this function as a string. JSON
|
|
36
|
+
// encoding is what keeps a stray quote from closing the literal and turning the rest of an id
|
|
37
|
+
// into executable script — the value still appears verbatim, and that is fine; what matters is
|
|
38
|
+
// that a quote inside it is ESCAPED rather than terminating the string.
|
|
39
|
+
const script = gtmHeadScript({ id: `${ID}"+alert(1)+"`, dataLayerName: 'owlLayer' })
|
|
40
|
+
|
|
41
|
+
expect(script).toContain(JSON.stringify(`${ID}"+alert(1)+"`))
|
|
42
|
+
expect(script).toContain(JSON.stringify('owlLayer'))
|
|
43
|
+
// The escaped form is what makes it inert; the bare form would have closed the literal.
|
|
44
|
+
expect(script).toContain('\\"+alert(1)+\\"')
|
|
45
|
+
expect(script).not.toContain(`"${ID}"+alert(1)+""`)
|
|
46
|
+
})
|
|
47
|
+
|
|
48
|
+
test('a custom queue name is passed to the container', async () => {
|
|
49
|
+
expect(gtmHeadScript({ id: ID, dataLayerName: 'owlLayer' })).toContain("l!='dataLayer'")
|
|
50
|
+
expect(gtmHeadScript({ id: ID })).toContain(JSON.stringify('dataLayer'))
|
|
51
|
+
})
|
|
52
|
+
})
|
|
53
|
+
|
|
54
|
+
describe('@owlmeans/web-gtm — the noscript frame', () => {
|
|
55
|
+
test('it names the container and stays invisible', async () => {
|
|
56
|
+
const frame = gtmNoscriptFrame({ id: ID })
|
|
57
|
+
|
|
58
|
+
expect(frame).toContain(`id=${ID}`)
|
|
59
|
+
expect(frame).toContain('display:none')
|
|
60
|
+
})
|
|
61
|
+
|
|
62
|
+
test('an id is URL-encoded, so it cannot break out of the attribute', async () => {
|
|
63
|
+
expect(gtmNoscriptFrame({ id: 'a"b' })).not.toContain('a"b')
|
|
64
|
+
})
|
|
65
|
+
})
|
package/tsconfig.json
ADDED