form-attribution 1.0.0
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/LICENSE.md +201 -0
- package/README.md +227 -0
- package/dist/script.js +859 -0
- package/package.json +46 -0
package/LICENSE.md
ADDED
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
+
|
|
7
|
+
1. Definitions.
|
|
8
|
+
|
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
10
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
11
|
+
|
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
13
|
+
the copyright owner that is granting the License.
|
|
14
|
+
|
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
16
|
+
other entities that control, are controlled by, or are under common
|
|
17
|
+
control with that entity. For the purposes of this definition,
|
|
18
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
19
|
+
direction or management of such entity, whether by contract or
|
|
20
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
21
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
22
|
+
|
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
24
|
+
exercising permissions granted by this License.
|
|
25
|
+
|
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
27
|
+
including but not limited to software source code, documentation
|
|
28
|
+
source, and configuration files.
|
|
29
|
+
|
|
30
|
+
"Object" form shall mean any form resulting from mechanical
|
|
31
|
+
transformation or translation of a Source form, including but
|
|
32
|
+
not limited to compiled object code, generated documentation,
|
|
33
|
+
and conversions to other media types.
|
|
34
|
+
|
|
35
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
36
|
+
Object form, made available under the License, as indicated by a
|
|
37
|
+
copyright notice that is included in or attached to the work
|
|
38
|
+
(an example is provided in the Appendix below).
|
|
39
|
+
|
|
40
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
41
|
+
form, that is based on (or derived from) the Work and for which the
|
|
42
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
43
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
44
|
+
of this License, Derivative Works shall not include works that remain
|
|
45
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
46
|
+
the Work and Derivative Works thereof.
|
|
47
|
+
|
|
48
|
+
"Contribution" shall mean any work of authorship, including
|
|
49
|
+
the original version of the Work and any modifications or additions
|
|
50
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
51
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
52
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
53
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
54
|
+
means any form of electronic, verbal, or written communication sent
|
|
55
|
+
to the Licensor or its representatives, including but not limited to
|
|
56
|
+
communication on electronic mailing lists, source code control systems,
|
|
57
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
58
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
59
|
+
excluding communication that is conspicuously marked or otherwise
|
|
60
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
61
|
+
|
|
62
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
63
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
64
|
+
subsequently incorporated within the Work.
|
|
65
|
+
|
|
66
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
67
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
68
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
69
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
70
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
71
|
+
Work and such Derivative Works in Source or Object form.
|
|
72
|
+
|
|
73
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
74
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
75
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
76
|
+
(except as stated in this section) patent license to make, have made,
|
|
77
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
78
|
+
where such license applies only to those patent claims licensable
|
|
79
|
+
by such Contributor that are necessarily infringed by their
|
|
80
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
81
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
82
|
+
institute patent litigation against any entity (including a
|
|
83
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
84
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
85
|
+
or contributory patent infringement, then any patent licenses
|
|
86
|
+
granted to You under this License for that Work shall terminate
|
|
87
|
+
as of the date such litigation is filed.
|
|
88
|
+
|
|
89
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
90
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
91
|
+
modifications, and in Source or Object form, provided that You
|
|
92
|
+
meet the following conditions:
|
|
93
|
+
|
|
94
|
+
(a) You must give any other recipients of the Work or
|
|
95
|
+
Derivative Works a copy of this License; and
|
|
96
|
+
|
|
97
|
+
(b) You must cause any modified files to carry prominent notices
|
|
98
|
+
stating that You changed the files; and
|
|
99
|
+
|
|
100
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
101
|
+
that You distribute, all copyright, patent, trademark, and
|
|
102
|
+
attribution notices from the Source form of the Work,
|
|
103
|
+
excluding those notices that do not pertain to any part of
|
|
104
|
+
the Derivative Works; and
|
|
105
|
+
|
|
106
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
107
|
+
distribution, then any Derivative Works that You distribute must
|
|
108
|
+
include a readable copy of the attribution notices contained
|
|
109
|
+
within such NOTICE file, excluding those notices that do not
|
|
110
|
+
pertain to any part of the Derivative Works, in at least one
|
|
111
|
+
of the following places: within a NOTICE text file distributed
|
|
112
|
+
as part of the Derivative Works; within the Source form or
|
|
113
|
+
documentation, if provided along with the Derivative Works; or,
|
|
114
|
+
within a display generated by the Derivative Works, if and
|
|
115
|
+
wherever such third-party notices normally appear. The contents
|
|
116
|
+
of the NOTICE file are for informational purposes only and
|
|
117
|
+
do not modify the License. You may add Your own attribution
|
|
118
|
+
notices within Derivative Works that You distribute, alongside
|
|
119
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
120
|
+
that such additional attribution notices cannot be construed
|
|
121
|
+
as modifying the License.
|
|
122
|
+
|
|
123
|
+
You may add Your own copyright statement to Your modifications and
|
|
124
|
+
may provide additional or different license terms and conditions
|
|
125
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
126
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
127
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
128
|
+
the conditions stated in this License.
|
|
129
|
+
|
|
130
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
131
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
132
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
133
|
+
this License, without any additional terms or conditions.
|
|
134
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
135
|
+
the terms of any separate license agreement you may have executed
|
|
136
|
+
with Licensor regarding such Contributions.
|
|
137
|
+
|
|
138
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
139
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
140
|
+
except as required for reasonable and customary use in describing the
|
|
141
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
142
|
+
|
|
143
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
144
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
145
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
146
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
147
|
+
implied, including, without limitation, any warranties or conditions
|
|
148
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
149
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
150
|
+
appropriateness of using or redistributing the Work and assume any
|
|
151
|
+
risks associated with Your exercise of permissions under this License.
|
|
152
|
+
|
|
153
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
154
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
155
|
+
unless required by applicable law (such as deliberate and grossly
|
|
156
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
157
|
+
liable to You for damages, including any direct, indirect, special,
|
|
158
|
+
incidental, or consequential damages of any character arising as a
|
|
159
|
+
result of this License or out of the use or inability to use the
|
|
160
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
161
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
162
|
+
other commercial damages or losses), even if such Contributor
|
|
163
|
+
has been advised of the possibility of such damages.
|
|
164
|
+
|
|
165
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
166
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
167
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
168
|
+
or other liability obligations and/or rights consistent with this
|
|
169
|
+
License. However, in accepting such obligations, You may act only
|
|
170
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
171
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
172
|
+
defend, and hold each Contributor harmless for any liability
|
|
173
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
174
|
+
of your accepting any such warranty or additional liability.
|
|
175
|
+
|
|
176
|
+
END OF TERMS AND CONDITIONS
|
|
177
|
+
|
|
178
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
179
|
+
|
|
180
|
+
To apply the Apache License to your work, attach the following
|
|
181
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
182
|
+
replaced with your own identifying information. (Don't include
|
|
183
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
184
|
+
comment syntax for the file format. We also recommend that a
|
|
185
|
+
file or class name and description of purpose be included on the
|
|
186
|
+
same "printed page" as the copyright notice for easier
|
|
187
|
+
identification within third-party archives.
|
|
188
|
+
|
|
189
|
+
Copyright 2025 Ben Sabic
|
|
190
|
+
|
|
191
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
192
|
+
you may not use this file except in compliance with the License.
|
|
193
|
+
You may obtain a copy of the License at
|
|
194
|
+
|
|
195
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
196
|
+
|
|
197
|
+
Unless required by applicable law or agreed to in writing, software
|
|
198
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
199
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
200
|
+
See the License for the specific language governing permissions and
|
|
201
|
+
limitations under the License.
|
package/README.md
ADDED
|
@@ -0,0 +1,227 @@
|
|
|
1
|
+
# form-attribution
|
|
2
|
+
|
|
3
|
+
Automatically capture and persist marketing attribution parameters (UTM tags, referrer data, landing pages) and inject them into HTML forms as hidden fields.
|
|
4
|
+
|
|
5
|
+
## Features
|
|
6
|
+
|
|
7
|
+
- **Zero dependencies** - Self-contained script using only browser APIs
|
|
8
|
+
- **Automatic capture** - Captures UTM parameters, referrer, landing page, and timestamps
|
|
9
|
+
- **Persistent storage** - Stores attribution data across page visits with smart fallbacks
|
|
10
|
+
- **Form injection** - Injects hidden fields into all forms automatically
|
|
11
|
+
- **Dynamic form support** - Detects and injects into dynamically added forms via MutationObserver
|
|
12
|
+
- **First-touch attribution** - Preserves initial attribution data across subsequent visits
|
|
13
|
+
- **Privacy-respecting** - Honors Global Privacy Control (GPC) and Do Not Track (DNT) signals
|
|
14
|
+
- **XSS-safe** - Sanitizes all values before injection
|
|
15
|
+
|
|
16
|
+
## Installation
|
|
17
|
+
|
|
18
|
+
### CDN
|
|
19
|
+
|
|
20
|
+
*jsDelivr:*
|
|
21
|
+
|
|
22
|
+
```html
|
|
23
|
+
<script src="https://cdn.jsdelivr.net/npm/form-attribution@latest/dist/script.min.js"></script>
|
|
24
|
+
```
|
|
25
|
+
|
|
26
|
+
*unpkg:*
|
|
27
|
+
|
|
28
|
+
```html
|
|
29
|
+
<script src="https://unpkg.com/form-attribution@latest/dist/script.min.js"></script>
|
|
30
|
+
```
|
|
31
|
+
|
|
32
|
+
## Quick Start
|
|
33
|
+
|
|
34
|
+
Add the script to your HTML before the closing `</body>` tag:
|
|
35
|
+
|
|
36
|
+
```html
|
|
37
|
+
<script src="https://cdn.jsdelivr.net/npm/form-attribution@latest/dist/script.min.js"></script>
|
|
38
|
+
```
|
|
39
|
+
|
|
40
|
+
That's it! The script will automatically:
|
|
41
|
+
|
|
42
|
+
1. Capture UTM parameters from the URL
|
|
43
|
+
2. Store them in sessionStorage
|
|
44
|
+
3. Inject hidden fields into all forms on the page
|
|
45
|
+
|
|
46
|
+
## Parameters Captured
|
|
47
|
+
|
|
48
|
+
### URL Parameters (default)
|
|
49
|
+
|
|
50
|
+
| Parameter | Description |
|
|
51
|
+
|-----------|-------------|
|
|
52
|
+
| `utm_source` | Traffic source (e.g., google, newsletter) |
|
|
53
|
+
| `utm_medium` | Marketing medium (e.g., cpc, email) |
|
|
54
|
+
| `utm_campaign` | Campaign name |
|
|
55
|
+
| `utm_term` | Paid search keywords |
|
|
56
|
+
| `utm_content` | Content variant for A/B testing |
|
|
57
|
+
| `utm_id` | Campaign ID |
|
|
58
|
+
| `ref` | Referrer tracking parameter |
|
|
59
|
+
|
|
60
|
+
### Metadata (automatically captured)
|
|
61
|
+
|
|
62
|
+
| Parameter | Description |
|
|
63
|
+
|-----------|-------------|
|
|
64
|
+
| `landing_page` | First page URL visited (without query string) |
|
|
65
|
+
| `current_page` | Current page URL (without query string) |
|
|
66
|
+
| `referrer_url` | Document referrer |
|
|
67
|
+
| `first_touch_timestamp` | ISO 8601 timestamp of first visit |
|
|
68
|
+
|
|
69
|
+
## Configuration
|
|
70
|
+
|
|
71
|
+
Configure the script using `data-*` attributes on the script tag:
|
|
72
|
+
|
|
73
|
+
```html
|
|
74
|
+
<script src="/dist/script.js"
|
|
75
|
+
data-storage="sessionStorage"
|
|
76
|
+
data-field-prefix="attr_"
|
|
77
|
+
data-extra-params="gclid,fbclid"
|
|
78
|
+
data-exclude-forms=".no-track"
|
|
79
|
+
data-debug="true">
|
|
80
|
+
</script>
|
|
81
|
+
```
|
|
82
|
+
|
|
83
|
+
### Options
|
|
84
|
+
|
|
85
|
+
| Attribute | Default | Description |
|
|
86
|
+
|-----------|---------|-------------|
|
|
87
|
+
| `data-storage` | `sessionStorage` | Storage method: `sessionStorage`, `localStorage`, or `cookie` |
|
|
88
|
+
| `data-field-prefix` | `""` | Prefix for hidden field names (e.g., `attr_` creates `attr_utm_source`) |
|
|
89
|
+
| `data-extra-params` | `""` | Comma-separated list of additional URL parameters to capture |
|
|
90
|
+
| `data-exclude-forms` | `""` | CSS selector for forms to exclude from injection |
|
|
91
|
+
| `data-storage-key` | `form_attribution_data` | Custom key name for stored data |
|
|
92
|
+
| `data-debug` | `false` | Enable console logging |
|
|
93
|
+
|
|
94
|
+
### Cookie Options
|
|
95
|
+
|
|
96
|
+
When using `data-storage="cookie"`:
|
|
97
|
+
|
|
98
|
+
| Attribute | Default | Description |
|
|
99
|
+
|-----------|---------|-------------|
|
|
100
|
+
| `data-cookie-domain` | `""` | Cookie domain (e.g., `.example.com`) |
|
|
101
|
+
| `data-cookie-path` | `/` | Cookie path |
|
|
102
|
+
| `data-cookie-expires` | `30` | Expiration in days |
|
|
103
|
+
| `data-cookie-samesite` | `lax` | SameSite policy: `lax`, `strict`, or `none` |
|
|
104
|
+
|
|
105
|
+
## Usage Examples
|
|
106
|
+
|
|
107
|
+
### Capture Google and Facebook Click IDs
|
|
108
|
+
|
|
109
|
+
```html
|
|
110
|
+
<script src="/dist/script.js"
|
|
111
|
+
data-extra-params="gclid,fbclid,msclkid">
|
|
112
|
+
</script>
|
|
113
|
+
```
|
|
114
|
+
|
|
115
|
+
### Use localStorage for Longer Persistence
|
|
116
|
+
|
|
117
|
+
```html
|
|
118
|
+
<script src="/dist/script.js"
|
|
119
|
+
data-storage="localStorage">
|
|
120
|
+
</script>
|
|
121
|
+
```
|
|
122
|
+
|
|
123
|
+
### Use Cookies for Cross-Subdomain Tracking
|
|
124
|
+
|
|
125
|
+
```html
|
|
126
|
+
<script src="/dist/script.js"
|
|
127
|
+
data-storage="cookie"
|
|
128
|
+
data-cookie-domain=".example.com"
|
|
129
|
+
data-cookie-expires="90">
|
|
130
|
+
</script>
|
|
131
|
+
```
|
|
132
|
+
|
|
133
|
+
### Exclude Specific Forms
|
|
134
|
+
|
|
135
|
+
```html
|
|
136
|
+
<script src="/dist/script.js"
|
|
137
|
+
data-exclude-forms=".login-form, [data-no-attribution]">
|
|
138
|
+
</script>
|
|
139
|
+
```
|
|
140
|
+
|
|
141
|
+
### Add Field Prefix for CRM Compatibility
|
|
142
|
+
|
|
143
|
+
```html
|
|
144
|
+
<script src="/dist/script.js"
|
|
145
|
+
data-field-prefix="lead_">
|
|
146
|
+
</script>
|
|
147
|
+
```
|
|
148
|
+
|
|
149
|
+
This creates fields like `lead_utm_source`, `lead_utm_medium`, etc.
|
|
150
|
+
|
|
151
|
+
## Script Builder
|
|
152
|
+
|
|
153
|
+
Use the interactive [Script Builder](script-builder/index.html) tool to generate a configured script tag with a visual interface.
|
|
154
|
+
|
|
155
|
+
## Storage Fallback Chain
|
|
156
|
+
|
|
157
|
+
The script uses intelligent fallback when storage is unavailable:
|
|
158
|
+
|
|
159
|
+
| Requested | Fallback Chain |
|
|
160
|
+
|-----------|----------------|
|
|
161
|
+
| `localStorage` | localStorage → sessionStorage → cookie → memory |
|
|
162
|
+
| `sessionStorage` | sessionStorage → cookie → memory |
|
|
163
|
+
| `cookie` | cookie → memory |
|
|
164
|
+
|
|
165
|
+
## Privacy
|
|
166
|
+
|
|
167
|
+
The script respects user privacy preferences:
|
|
168
|
+
|
|
169
|
+
- **Global Privacy Control (GPC)** - Disables tracking when `navigator.globalPrivacyControl` is true
|
|
170
|
+
- **Do Not Track (DNT)** - Disables tracking when DNT is enabled
|
|
171
|
+
|
|
172
|
+
When privacy signals are detected, no data is captured or stored.
|
|
173
|
+
|
|
174
|
+
## Injected Fields
|
|
175
|
+
|
|
176
|
+
Hidden fields are injected with the following attributes:
|
|
177
|
+
|
|
178
|
+
```html
|
|
179
|
+
<input type="hidden"
|
|
180
|
+
name="utm_source"
|
|
181
|
+
value="google"
|
|
182
|
+
data-form-attribution="true"
|
|
183
|
+
data-form-attribution-managed="true">
|
|
184
|
+
```
|
|
185
|
+
|
|
186
|
+
- Existing hidden fields with matching names are updated (no duplicates created)
|
|
187
|
+
- User-visible form fields are never modified
|
|
188
|
+
- All values are HTML-entity encoded for XSS protection
|
|
189
|
+
|
|
190
|
+
## Development
|
|
191
|
+
|
|
192
|
+
### Prerequisites
|
|
193
|
+
|
|
194
|
+
- Node.js
|
|
195
|
+
- pnpm
|
|
196
|
+
|
|
197
|
+
### Setup
|
|
198
|
+
|
|
199
|
+
```bash
|
|
200
|
+
pnpm install
|
|
201
|
+
```
|
|
202
|
+
|
|
203
|
+
### Commands
|
|
204
|
+
|
|
205
|
+
```bash
|
|
206
|
+
pnpm test # Run Playwright tests (Chromium, Firefox, WebKit)
|
|
207
|
+
pnpm exec playwright test --ui # Run tests with interactive UI
|
|
208
|
+
pnpm check # Lint with Biome
|
|
209
|
+
pnpm fix # Auto-fix lint issues
|
|
210
|
+
```
|
|
211
|
+
|
|
212
|
+
## Browser Support
|
|
213
|
+
|
|
214
|
+
The script uses standard browser APIs with graceful fallbacks:
|
|
215
|
+
|
|
216
|
+
- URL API for query parameter parsing
|
|
217
|
+
- MutationObserver for dynamic form detection
|
|
218
|
+
- Web Storage API (sessionStorage/localStorage)
|
|
219
|
+
- CookieStore API with legacy `document.cookie` fallback
|
|
220
|
+
|
|
221
|
+
## License
|
|
222
|
+
|
|
223
|
+
[Apache-2.0](LICENSE.md)
|
|
224
|
+
|
|
225
|
+
## Author
|
|
226
|
+
|
|
227
|
+
[Ben Sabic](https://bensabic.ca)
|
package/dist/script.js
ADDED
|
@@ -0,0 +1,859 @@
|
|
|
1
|
+
(() => {
|
|
2
|
+
const SCRIPT_ELEMENT =
|
|
3
|
+
document.currentScript ??
|
|
4
|
+
[...document.scripts]
|
|
5
|
+
.reverse()
|
|
6
|
+
.find((s) => {
|
|
7
|
+
const src = s.getAttribute("src") || "";
|
|
8
|
+
return (
|
|
9
|
+
src.includes("cdn.jsdelivr.net/npm/form-attribution@") &&
|
|
10
|
+
src.endsWith("/dist/script.min.js")
|
|
11
|
+
);
|
|
12
|
+
}) ??
|
|
13
|
+
null;
|
|
14
|
+
|
|
15
|
+
const DEFAULT_PARAMS = [
|
|
16
|
+
"utm_source",
|
|
17
|
+
"utm_medium",
|
|
18
|
+
"utm_campaign",
|
|
19
|
+
"utm_term",
|
|
20
|
+
"utm_content",
|
|
21
|
+
"utm_id",
|
|
22
|
+
"ref",
|
|
23
|
+
];
|
|
24
|
+
|
|
25
|
+
const META_PARAMS = [
|
|
26
|
+
"landing_page",
|
|
27
|
+
"current_page",
|
|
28
|
+
"referrer_url",
|
|
29
|
+
"first_touch_timestamp",
|
|
30
|
+
];
|
|
31
|
+
|
|
32
|
+
const VALID_STORAGE_TYPES = ["sessionStorage", "localStorage", "cookie"];
|
|
33
|
+
const VALID_SAMESITE_VALUES = ["lax", "strict", "none"];
|
|
34
|
+
const MAX_COOKIE_SIZE = 4000;
|
|
35
|
+
const MAX_PARAM_LENGTH = 500;
|
|
36
|
+
const MAX_URL_LENGTH = 2000;
|
|
37
|
+
|
|
38
|
+
const safeParse = (data) => {
|
|
39
|
+
const parsed = JSON.parse(data);
|
|
40
|
+
if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) {
|
|
41
|
+
const safe = Object.create(null);
|
|
42
|
+
for (const key of Object.keys(parsed)) {
|
|
43
|
+
if (key !== "__proto__" && key !== "constructor" && key !== "prototype") {
|
|
44
|
+
safe[key] = parsed[key];
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
return safe;
|
|
48
|
+
}
|
|
49
|
+
return parsed;
|
|
50
|
+
};
|
|
51
|
+
|
|
52
|
+
const sanitizeValue = (val) => {
|
|
53
|
+
return String(val).replace(/[<>'"]/g, (char) => {
|
|
54
|
+
const entities = { "<": "<", ">": ">", "'": "'", '"': """ };
|
|
55
|
+
return entities[char];
|
|
56
|
+
});
|
|
57
|
+
};
|
|
58
|
+
|
|
59
|
+
const validateStorageKey = (key) => {
|
|
60
|
+
const safeKey = String(key ?? "form_attribution_data").trim();
|
|
61
|
+
return /^[a-zA-Z0-9_-]+$/.test(safeKey) ? safeKey : "form_attribution_data";
|
|
62
|
+
};
|
|
63
|
+
|
|
64
|
+
const validateFieldPrefix = (prefix) => {
|
|
65
|
+
const safePrefix = String(prefix ?? "").trim();
|
|
66
|
+
return /^[a-zA-Z0-9_-]*$/.test(safePrefix) ? safePrefix : "";
|
|
67
|
+
};
|
|
68
|
+
|
|
69
|
+
const validateCookiePath = (path) => {
|
|
70
|
+
const safePath = String(path ?? "/").trim();
|
|
71
|
+
return safePath.startsWith("/") && !/[;\s]/.test(safePath) ? safePath : "/";
|
|
72
|
+
};
|
|
73
|
+
|
|
74
|
+
const validateExcludeForms = (selector) => {
|
|
75
|
+
if (!selector) {
|
|
76
|
+
return "";
|
|
77
|
+
}
|
|
78
|
+
const safe = String(selector ?? "").trim();
|
|
79
|
+
if (!/^[a-zA-Z0-9._#\[\]="':\s,>+~-]*$/.test(safe)) {
|
|
80
|
+
return "";
|
|
81
|
+
}
|
|
82
|
+
return safe;
|
|
83
|
+
};
|
|
84
|
+
|
|
85
|
+
const validateCookieDomain = (domain) => {
|
|
86
|
+
if (!domain) {
|
|
87
|
+
return undefined;
|
|
88
|
+
}
|
|
89
|
+
const safeDomain = String(domain).trim().toLowerCase();
|
|
90
|
+
if (!safeDomain) {
|
|
91
|
+
return undefined;
|
|
92
|
+
}
|
|
93
|
+
const currentHost = window.location.hostname.toLowerCase();
|
|
94
|
+
|
|
95
|
+
// Must be exact match or a parent domain of current host
|
|
96
|
+
if (safeDomain === currentHost) {
|
|
97
|
+
return safeDomain;
|
|
98
|
+
}
|
|
99
|
+
if (currentHost.endsWith("." + safeDomain)) {
|
|
100
|
+
return safeDomain;
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
return undefined;
|
|
104
|
+
};
|
|
105
|
+
|
|
106
|
+
const parseExtraParams = (value) => {
|
|
107
|
+
if (!value) {
|
|
108
|
+
return [];
|
|
109
|
+
}
|
|
110
|
+
const safeValue = String(value ?? "").trim();
|
|
111
|
+
return safeValue
|
|
112
|
+
? safeValue
|
|
113
|
+
.split(",")
|
|
114
|
+
.map((p) => p.trim())
|
|
115
|
+
.filter(Boolean)
|
|
116
|
+
: [];
|
|
117
|
+
};
|
|
118
|
+
|
|
119
|
+
const parseStorageType = (value) => {
|
|
120
|
+
const raw = String(value ?? "sessionStorage").trim();
|
|
121
|
+
return VALID_STORAGE_TYPES.includes(raw) ? raw : "sessionStorage";
|
|
122
|
+
};
|
|
123
|
+
|
|
124
|
+
const parseCookieExpires = (value) => {
|
|
125
|
+
const raw = Number.parseInt(value ?? "30", 10);
|
|
126
|
+
return Number.isFinite(raw) && raw >= 0 ? raw : 30;
|
|
127
|
+
};
|
|
128
|
+
|
|
129
|
+
const parseSameSite = (value) => {
|
|
130
|
+
const raw = String(value ?? "lax")
|
|
131
|
+
.trim()
|
|
132
|
+
.toLowerCase();
|
|
133
|
+
return VALID_SAMESITE_VALUES.includes(raw) ? raw : "lax";
|
|
134
|
+
};
|
|
135
|
+
|
|
136
|
+
const getConfig = () => {
|
|
137
|
+
const dataset = SCRIPT_ELEMENT?.dataset ?? {};
|
|
138
|
+
|
|
139
|
+
return {
|
|
140
|
+
storage: parseStorageType(dataset.storage),
|
|
141
|
+
cookieDomain: validateCookieDomain(dataset.cookieDomain),
|
|
142
|
+
cookiePath: validateCookiePath(dataset.cookiePath),
|
|
143
|
+
cookieExpires: parseCookieExpires(dataset.cookieExpires),
|
|
144
|
+
cookieSameSite: parseSameSite(dataset.cookieSamesite),
|
|
145
|
+
fieldPrefix: validateFieldPrefix(dataset.fieldPrefix),
|
|
146
|
+
extraParams: parseExtraParams(dataset.extraParams),
|
|
147
|
+
excludeForms: validateExcludeForms(dataset.excludeForms),
|
|
148
|
+
debug: dataset.debug === "true",
|
|
149
|
+
storageKey: validateStorageKey(dataset.storageKey),
|
|
150
|
+
};
|
|
151
|
+
};
|
|
152
|
+
|
|
153
|
+
const CONFIG = getConfig();
|
|
154
|
+
const TRACKED_PARAMS = [
|
|
155
|
+
...new Set([...DEFAULT_PARAMS, ...CONFIG.extraParams]),
|
|
156
|
+
];
|
|
157
|
+
const PARAMS_TO_INJECT = [...new Set([...TRACKED_PARAMS, ...META_PARAMS])];
|
|
158
|
+
|
|
159
|
+
const log = (...args) => {
|
|
160
|
+
if (CONFIG.debug) {
|
|
161
|
+
console.log("[FormAttribution]", ...args);
|
|
162
|
+
}
|
|
163
|
+
};
|
|
164
|
+
|
|
165
|
+
const parseUrlParams = (url) => {
|
|
166
|
+
try {
|
|
167
|
+
const urlObj = new URL(url, window.location.origin);
|
|
168
|
+
return Object.fromEntries(urlObj.searchParams.entries());
|
|
169
|
+
} catch {
|
|
170
|
+
return {};
|
|
171
|
+
}
|
|
172
|
+
};
|
|
173
|
+
|
|
174
|
+
const isPrivacySignalEnabled = () => {
|
|
175
|
+
if (navigator.globalPrivacyControl === true) {
|
|
176
|
+
return true;
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
const dnt = navigator.doNotTrack || window.doNotTrack;
|
|
180
|
+
return dnt === "1" || dnt === "yes";
|
|
181
|
+
};
|
|
182
|
+
|
|
183
|
+
const createMemoryAdapter = () => {
|
|
184
|
+
const map = new Map();
|
|
185
|
+
|
|
186
|
+
return {
|
|
187
|
+
get(key) {
|
|
188
|
+
return Promise.resolve(map.has(key) ? map.get(key) : null);
|
|
189
|
+
},
|
|
190
|
+
|
|
191
|
+
set(key, value) {
|
|
192
|
+
map.set(key, value);
|
|
193
|
+
return Promise.resolve(true);
|
|
194
|
+
},
|
|
195
|
+
|
|
196
|
+
remove(key) {
|
|
197
|
+
map.delete(key);
|
|
198
|
+
return Promise.resolve(true);
|
|
199
|
+
},
|
|
200
|
+
};
|
|
201
|
+
};
|
|
202
|
+
|
|
203
|
+
const getUsableWebStorage = (type) => {
|
|
204
|
+
try {
|
|
205
|
+
const storage = window[type];
|
|
206
|
+
if (!storage) {
|
|
207
|
+
return null;
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
const testKey = "__form_attribution_test__";
|
|
211
|
+
storage.setItem(testKey, testKey);
|
|
212
|
+
storage.removeItem(testKey);
|
|
213
|
+
return storage;
|
|
214
|
+
} catch {
|
|
215
|
+
return null;
|
|
216
|
+
}
|
|
217
|
+
};
|
|
218
|
+
|
|
219
|
+
const getStorageCandidates = (requested) => {
|
|
220
|
+
if (requested === "localStorage") {
|
|
221
|
+
return ["localStorage", "sessionStorage", "cookie", "memory"];
|
|
222
|
+
}
|
|
223
|
+
if (requested === "sessionStorage") {
|
|
224
|
+
return ["sessionStorage", "cookie", "memory"];
|
|
225
|
+
}
|
|
226
|
+
if (requested === "cookie") {
|
|
227
|
+
return ["cookie", "memory"];
|
|
228
|
+
}
|
|
229
|
+
return ["sessionStorage", "cookie", "memory"];
|
|
230
|
+
};
|
|
231
|
+
|
|
232
|
+
const tryCreateAdapter = (candidate) => {
|
|
233
|
+
if (candidate === "cookie") {
|
|
234
|
+
log("Using cookie storage");
|
|
235
|
+
return createCookieAdapter();
|
|
236
|
+
}
|
|
237
|
+
if (candidate === "memory") {
|
|
238
|
+
log("Using in-memory storage");
|
|
239
|
+
return createMemoryAdapter();
|
|
240
|
+
}
|
|
241
|
+
const storage = getUsableWebStorage(candidate);
|
|
242
|
+
if (storage) {
|
|
243
|
+
log(`Using ${candidate} storage`);
|
|
244
|
+
return createWebStorageAdapter(storage);
|
|
245
|
+
}
|
|
246
|
+
return null;
|
|
247
|
+
};
|
|
248
|
+
|
|
249
|
+
const createStorageAdapter = (type) => {
|
|
250
|
+
const requested = String(type ?? "").trim();
|
|
251
|
+
const candidates = getStorageCandidates(requested);
|
|
252
|
+
|
|
253
|
+
for (const candidate of candidates) {
|
|
254
|
+
const adapter = tryCreateAdapter(candidate);
|
|
255
|
+
if (adapter) {
|
|
256
|
+
return adapter;
|
|
257
|
+
}
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
log("Falling back to in-memory storage");
|
|
261
|
+
return createMemoryAdapter();
|
|
262
|
+
};
|
|
263
|
+
|
|
264
|
+
const createWebStorageAdapter = (storage) => ({
|
|
265
|
+
get(key) {
|
|
266
|
+
try {
|
|
267
|
+
const data = storage.getItem(key);
|
|
268
|
+
return Promise.resolve(data ? safeParse(data) : null);
|
|
269
|
+
} catch (e) {
|
|
270
|
+
log("Storage get error:", e);
|
|
271
|
+
return Promise.resolve(null);
|
|
272
|
+
}
|
|
273
|
+
},
|
|
274
|
+
|
|
275
|
+
set(key, value) {
|
|
276
|
+
try {
|
|
277
|
+
storage.setItem(key, JSON.stringify(value));
|
|
278
|
+
return Promise.resolve(true);
|
|
279
|
+
} catch (e) {
|
|
280
|
+
log("Storage set error:", e);
|
|
281
|
+
return Promise.resolve(false);
|
|
282
|
+
}
|
|
283
|
+
},
|
|
284
|
+
|
|
285
|
+
remove(key) {
|
|
286
|
+
try {
|
|
287
|
+
storage.removeItem(key);
|
|
288
|
+
return Promise.resolve(true);
|
|
289
|
+
} catch (e) {
|
|
290
|
+
log("Storage remove error:", e);
|
|
291
|
+
return Promise.resolve(false);
|
|
292
|
+
}
|
|
293
|
+
},
|
|
294
|
+
});
|
|
295
|
+
|
|
296
|
+
const createCookieAdapter = () => {
|
|
297
|
+
const fallback = createMemoryAdapter();
|
|
298
|
+
let primaryWriteFailed = false;
|
|
299
|
+
let cookieStoreApi = null;
|
|
300
|
+
|
|
301
|
+
try {
|
|
302
|
+
cookieStoreApi = window.cookieStore ?? null;
|
|
303
|
+
} catch {
|
|
304
|
+
cookieStoreApi = null;
|
|
305
|
+
}
|
|
306
|
+
|
|
307
|
+
const useCookieStore = Boolean(
|
|
308
|
+
cookieStoreApi &&
|
|
309
|
+
typeof cookieStoreApi.get === "function" &&
|
|
310
|
+
typeof cookieStoreApi.set === "function" &&
|
|
311
|
+
typeof cookieStoreApi.delete === "function"
|
|
312
|
+
);
|
|
313
|
+
|
|
314
|
+
let forceLegacy = !useCookieStore;
|
|
315
|
+
|
|
316
|
+
const getExpirationDate = () => {
|
|
317
|
+
const date = new Date();
|
|
318
|
+
date.setDate(date.getDate() + CONFIG.cookieExpires);
|
|
319
|
+
return date;
|
|
320
|
+
};
|
|
321
|
+
|
|
322
|
+
const shouldUseSecure =
|
|
323
|
+
CONFIG.cookieSameSite === "none" || window.location.protocol === "https:";
|
|
324
|
+
|
|
325
|
+
const getSameSiteForCookieString = () => {
|
|
326
|
+
switch (CONFIG.cookieSameSite) {
|
|
327
|
+
case "strict":
|
|
328
|
+
return "Strict";
|
|
329
|
+
case "none":
|
|
330
|
+
return "None";
|
|
331
|
+
default:
|
|
332
|
+
return "Lax";
|
|
333
|
+
}
|
|
334
|
+
};
|
|
335
|
+
|
|
336
|
+
const legacyCookieAdapter = {
|
|
337
|
+
async get(key) {
|
|
338
|
+
try {
|
|
339
|
+
if (primaryWriteFailed) {
|
|
340
|
+
return await fallback.get(key);
|
|
341
|
+
}
|
|
342
|
+
|
|
343
|
+
const cookies = document.cookie.split(";");
|
|
344
|
+
for (const cookie of cookies) {
|
|
345
|
+
const [name, ...valueParts] = cookie.trim().split("=");
|
|
346
|
+
if (name === key) {
|
|
347
|
+
const value = valueParts.join("=");
|
|
348
|
+
return safeParse(decodeURIComponent(value));
|
|
349
|
+
}
|
|
350
|
+
}
|
|
351
|
+
|
|
352
|
+
return await fallback.get(key);
|
|
353
|
+
} catch (e) {
|
|
354
|
+
log("Legacy cookie get error:", e);
|
|
355
|
+
return await fallback.get(key);
|
|
356
|
+
}
|
|
357
|
+
},
|
|
358
|
+
|
|
359
|
+
async set(key, value) {
|
|
360
|
+
try {
|
|
361
|
+
const encodedValue = encodeURIComponent(JSON.stringify(value));
|
|
362
|
+
const expires = getExpirationDate().toUTCString();
|
|
363
|
+
|
|
364
|
+
let cookieStr = `${key}=${encodedValue}; path=${CONFIG.cookiePath}; expires=${expires}; SameSite=${getSameSiteForCookieString()}`;
|
|
365
|
+
|
|
366
|
+
if (CONFIG.cookieDomain) {
|
|
367
|
+
cookieStr += `; domain=${CONFIG.cookieDomain}`;
|
|
368
|
+
}
|
|
369
|
+
|
|
370
|
+
if (shouldUseSecure) {
|
|
371
|
+
cookieStr += "; Secure";
|
|
372
|
+
}
|
|
373
|
+
|
|
374
|
+
if (cookieStr.length > MAX_COOKIE_SIZE) {
|
|
375
|
+
log(
|
|
376
|
+
`Cookie size (${cookieStr.length}) exceeds limit (${MAX_COOKIE_SIZE}), falling back to memory storage`
|
|
377
|
+
);
|
|
378
|
+
primaryWriteFailed = true;
|
|
379
|
+
await fallback.set(key, value);
|
|
380
|
+
return true;
|
|
381
|
+
}
|
|
382
|
+
|
|
383
|
+
// biome-ignore lint/suspicious/noDocumentCookie: Needed for legacy cookie fallback when CookieStore API isn't available.
|
|
384
|
+
document.cookie = cookieStr;
|
|
385
|
+
await fallback.set(key, value);
|
|
386
|
+
return true;
|
|
387
|
+
} catch (e) {
|
|
388
|
+
log("Legacy cookie set error:", e);
|
|
389
|
+
primaryWriteFailed = true;
|
|
390
|
+
await fallback.set(key, value);
|
|
391
|
+
return true;
|
|
392
|
+
}
|
|
393
|
+
},
|
|
394
|
+
|
|
395
|
+
async remove(key) {
|
|
396
|
+
try {
|
|
397
|
+
let cookieStr = `${key}=; path=${CONFIG.cookiePath}; expires=Thu, 01 Jan 1970 00:00:00 GMT; SameSite=${getSameSiteForCookieString()}`;
|
|
398
|
+
if (CONFIG.cookieDomain) {
|
|
399
|
+
cookieStr += `; domain=${CONFIG.cookieDomain}`;
|
|
400
|
+
}
|
|
401
|
+
|
|
402
|
+
if (shouldUseSecure) {
|
|
403
|
+
cookieStr += "; Secure";
|
|
404
|
+
}
|
|
405
|
+
|
|
406
|
+
// biome-ignore lint/suspicious/noDocumentCookie: Needed for legacy cookie fallback when CookieStore API isn't available.
|
|
407
|
+
document.cookie = cookieStr;
|
|
408
|
+
await fallback.remove(key);
|
|
409
|
+
return true;
|
|
410
|
+
} catch (e) {
|
|
411
|
+
log("Legacy cookie remove error:", e);
|
|
412
|
+
await fallback.remove(key);
|
|
413
|
+
return true;
|
|
414
|
+
}
|
|
415
|
+
},
|
|
416
|
+
};
|
|
417
|
+
|
|
418
|
+
const cookieStoreAdapter = {
|
|
419
|
+
async get(key) {
|
|
420
|
+
try {
|
|
421
|
+
if (primaryWriteFailed) {
|
|
422
|
+
return fallback.get(key);
|
|
423
|
+
}
|
|
424
|
+
|
|
425
|
+
if (forceLegacy) {
|
|
426
|
+
return legacyCookieAdapter.get(key);
|
|
427
|
+
}
|
|
428
|
+
|
|
429
|
+
const cookie = await cookieStoreApi.get(key);
|
|
430
|
+
if (cookie?.value) {
|
|
431
|
+
return safeParse(decodeURIComponent(cookie.value));
|
|
432
|
+
}
|
|
433
|
+
return fallback.get(key);
|
|
434
|
+
} catch (e) {
|
|
435
|
+
log("CookieStore get error:", e);
|
|
436
|
+
forceLegacy = true;
|
|
437
|
+
return legacyCookieAdapter.get(key);
|
|
438
|
+
}
|
|
439
|
+
},
|
|
440
|
+
|
|
441
|
+
async set(key, value) {
|
|
442
|
+
try {
|
|
443
|
+
if (forceLegacy) {
|
|
444
|
+
return legacyCookieAdapter.set(key, value);
|
|
445
|
+
}
|
|
446
|
+
|
|
447
|
+
const encodedValue = encodeURIComponent(JSON.stringify(value));
|
|
448
|
+
|
|
449
|
+
if (encodedValue.length > MAX_COOKIE_SIZE) {
|
|
450
|
+
log(
|
|
451
|
+
`Cookie value size (${encodedValue.length}) exceeds limit (${MAX_COOKIE_SIZE}), falling back to memory storage`
|
|
452
|
+
);
|
|
453
|
+
primaryWriteFailed = true;
|
|
454
|
+
await fallback.set(key, value);
|
|
455
|
+
return true;
|
|
456
|
+
}
|
|
457
|
+
|
|
458
|
+
const cookieOptions = {
|
|
459
|
+
name: key,
|
|
460
|
+
value: encodedValue,
|
|
461
|
+
path: CONFIG.cookiePath,
|
|
462
|
+
expires: getExpirationDate(),
|
|
463
|
+
sameSite: CONFIG.cookieSameSite,
|
|
464
|
+
secure: shouldUseSecure,
|
|
465
|
+
};
|
|
466
|
+
|
|
467
|
+
if (CONFIG.cookieDomain) {
|
|
468
|
+
cookieOptions.domain = CONFIG.cookieDomain;
|
|
469
|
+
}
|
|
470
|
+
|
|
471
|
+
await cookieStoreApi.set(cookieOptions);
|
|
472
|
+
await fallback.set(key, value);
|
|
473
|
+
return true;
|
|
474
|
+
} catch (e) {
|
|
475
|
+
log("CookieStore set error:", e);
|
|
476
|
+
forceLegacy = true;
|
|
477
|
+
return legacyCookieAdapter.set(key, value);
|
|
478
|
+
}
|
|
479
|
+
},
|
|
480
|
+
|
|
481
|
+
async remove(key) {
|
|
482
|
+
try {
|
|
483
|
+
if (forceLegacy) {
|
|
484
|
+
return legacyCookieAdapter.remove(key);
|
|
485
|
+
}
|
|
486
|
+
|
|
487
|
+
const deleteOptions = { name: key, path: CONFIG.cookiePath };
|
|
488
|
+
|
|
489
|
+
if (CONFIG.cookieDomain) {
|
|
490
|
+
deleteOptions.domain = CONFIG.cookieDomain;
|
|
491
|
+
}
|
|
492
|
+
|
|
493
|
+
await cookieStoreApi.delete(deleteOptions);
|
|
494
|
+
await fallback.remove(key);
|
|
495
|
+
return true;
|
|
496
|
+
} catch (e) {
|
|
497
|
+
log("CookieStore remove error:", e);
|
|
498
|
+
forceLegacy = true;
|
|
499
|
+
return legacyCookieAdapter.remove(key);
|
|
500
|
+
}
|
|
501
|
+
},
|
|
502
|
+
};
|
|
503
|
+
|
|
504
|
+
log(
|
|
505
|
+
`Using ${useCookieStore ? "CookieStore API" : "legacy document.cookie"}`
|
|
506
|
+
);
|
|
507
|
+
return useCookieStore ? cookieStoreAdapter : legacyCookieAdapter;
|
|
508
|
+
};
|
|
509
|
+
|
|
510
|
+
const captureAttributionData = () => {
|
|
511
|
+
const currentUrl = window.location.href;
|
|
512
|
+
const urlParams = parseUrlParams(currentUrl);
|
|
513
|
+
const trackedParams = TRACKED_PARAMS;
|
|
514
|
+
|
|
515
|
+
const attributionData = {};
|
|
516
|
+
|
|
517
|
+
for (const param of trackedParams) {
|
|
518
|
+
if (urlParams[param] !== undefined) {
|
|
519
|
+
attributionData[param] = String(urlParams[param]).substring(
|
|
520
|
+
0,
|
|
521
|
+
MAX_PARAM_LENGTH
|
|
522
|
+
);
|
|
523
|
+
}
|
|
524
|
+
}
|
|
525
|
+
|
|
526
|
+
attributionData.landing_page = currentUrl
|
|
527
|
+
.split("?")[0]
|
|
528
|
+
.substring(0, MAX_URL_LENGTH);
|
|
529
|
+
attributionData.referrer_url = (document.referrer || "").substring(
|
|
530
|
+
0,
|
|
531
|
+
MAX_URL_LENGTH
|
|
532
|
+
);
|
|
533
|
+
attributionData.first_touch_timestamp = new Date().toISOString();
|
|
534
|
+
|
|
535
|
+
return attributionData;
|
|
536
|
+
};
|
|
537
|
+
|
|
538
|
+
const mergeAttributionData = (existing, current) => {
|
|
539
|
+
if (!existing) {
|
|
540
|
+
return current;
|
|
541
|
+
}
|
|
542
|
+
|
|
543
|
+
const merged = { ...existing };
|
|
544
|
+
const trackedParams = TRACKED_PARAMS;
|
|
545
|
+
|
|
546
|
+
for (const param of trackedParams) {
|
|
547
|
+
if (current[param] !== undefined && existing[param] === undefined) {
|
|
548
|
+
merged[param] = current[param];
|
|
549
|
+
}
|
|
550
|
+
}
|
|
551
|
+
|
|
552
|
+
if (!merged.landing_page) {
|
|
553
|
+
merged.landing_page = current.landing_page;
|
|
554
|
+
}
|
|
555
|
+
|
|
556
|
+
if (!merged.referrer_url && current.referrer_url) {
|
|
557
|
+
merged.referrer_url = current.referrer_url;
|
|
558
|
+
}
|
|
559
|
+
|
|
560
|
+
if (!merged.first_touch_timestamp) {
|
|
561
|
+
merged.first_touch_timestamp = current.first_touch_timestamp;
|
|
562
|
+
}
|
|
563
|
+
|
|
564
|
+
return merged;
|
|
565
|
+
};
|
|
566
|
+
|
|
567
|
+
const shouldIncludeForm = (form) => {
|
|
568
|
+
if (!CONFIG.excludeForms) {
|
|
569
|
+
return true;
|
|
570
|
+
}
|
|
571
|
+
|
|
572
|
+
try {
|
|
573
|
+
return !form.matches(CONFIG.excludeForms);
|
|
574
|
+
} catch {
|
|
575
|
+
return true;
|
|
576
|
+
}
|
|
577
|
+
};
|
|
578
|
+
|
|
579
|
+
const getAttributionEntries = (data) => {
|
|
580
|
+
const entries = [];
|
|
581
|
+
|
|
582
|
+
if (!data || typeof data !== "object") {
|
|
583
|
+
return entries;
|
|
584
|
+
}
|
|
585
|
+
|
|
586
|
+
for (const param of PARAMS_TO_INJECT) {
|
|
587
|
+
if (param === "current_page") {
|
|
588
|
+
continue;
|
|
589
|
+
}
|
|
590
|
+
const value = data[param];
|
|
591
|
+
if (value !== undefined && value !== null && value !== "") {
|
|
592
|
+
entries.push({
|
|
593
|
+
name: `${CONFIG.fieldPrefix}${param}`,
|
|
594
|
+
value: String(value),
|
|
595
|
+
});
|
|
596
|
+
}
|
|
597
|
+
}
|
|
598
|
+
|
|
599
|
+
entries.push({
|
|
600
|
+
name: `${CONFIG.fieldPrefix}current_page`,
|
|
601
|
+
value: window.location.href.split("?")[0],
|
|
602
|
+
});
|
|
603
|
+
|
|
604
|
+
return entries;
|
|
605
|
+
};
|
|
606
|
+
|
|
607
|
+
const getTargetForms = () =>
|
|
608
|
+
Array.from(document.querySelectorAll("form")).filter(shouldIncludeForm);
|
|
609
|
+
|
|
610
|
+
const removeExistingFields = (form) => {
|
|
611
|
+
const existingFields = form.querySelectorAll(
|
|
612
|
+
'input[data-form-attribution="true"]'
|
|
613
|
+
);
|
|
614
|
+
|
|
615
|
+
for (const field of existingFields) {
|
|
616
|
+
field.remove();
|
|
617
|
+
}
|
|
618
|
+
};
|
|
619
|
+
|
|
620
|
+
const clearManagedFieldValues = (form) => {
|
|
621
|
+
const managedFields = form.querySelectorAll(
|
|
622
|
+
'input[type="hidden"][data-form-attribution-managed="true"]'
|
|
623
|
+
);
|
|
624
|
+
for (const field of managedFields) {
|
|
625
|
+
field.value = "";
|
|
626
|
+
}
|
|
627
|
+
};
|
|
628
|
+
|
|
629
|
+
const getFormElements = (form) => {
|
|
630
|
+
try {
|
|
631
|
+
return Object.getOwnPropertyDescriptor(
|
|
632
|
+
HTMLFormElement.prototype,
|
|
633
|
+
"elements"
|
|
634
|
+
).get.call(form);
|
|
635
|
+
} catch {
|
|
636
|
+
return form.elements;
|
|
637
|
+
}
|
|
638
|
+
};
|
|
639
|
+
|
|
640
|
+
const getHiddenInputsByName = (form, name) => {
|
|
641
|
+
const matches = [];
|
|
642
|
+
const elements = getFormElements(form);
|
|
643
|
+
if (!elements) {
|
|
644
|
+
return matches;
|
|
645
|
+
}
|
|
646
|
+
|
|
647
|
+
for (const el of elements) {
|
|
648
|
+
if (!el || el.tagName !== "INPUT") {
|
|
649
|
+
continue;
|
|
650
|
+
}
|
|
651
|
+
|
|
652
|
+
const input = el;
|
|
653
|
+
if (input.type === "hidden" && input.name === name) {
|
|
654
|
+
matches.push(input);
|
|
655
|
+
}
|
|
656
|
+
}
|
|
657
|
+
|
|
658
|
+
return matches;
|
|
659
|
+
};
|
|
660
|
+
|
|
661
|
+
const syncFormAttributionFields = (form, entries) => {
|
|
662
|
+
removeExistingFields(form);
|
|
663
|
+
|
|
664
|
+
if (!entries || entries.length === 0) {
|
|
665
|
+
clearManagedFieldValues(form);
|
|
666
|
+
return;
|
|
667
|
+
}
|
|
668
|
+
|
|
669
|
+
const fragment = document.createDocumentFragment();
|
|
670
|
+
|
|
671
|
+
for (const entry of entries) {
|
|
672
|
+
const existingInputs = getHiddenInputsByName(form, entry.name);
|
|
673
|
+
const safeValue = sanitizeValue(entry.value);
|
|
674
|
+
|
|
675
|
+
if (existingInputs.length > 0) {
|
|
676
|
+
for (const input of existingInputs) {
|
|
677
|
+
input.value = safeValue;
|
|
678
|
+
input.dataset.formAttributionManaged = "true";
|
|
679
|
+
}
|
|
680
|
+
|
|
681
|
+
continue;
|
|
682
|
+
}
|
|
683
|
+
|
|
684
|
+
const input = document.createElement("input");
|
|
685
|
+
input.type = "hidden";
|
|
686
|
+
input.name = entry.name;
|
|
687
|
+
input.value = safeValue;
|
|
688
|
+
|
|
689
|
+
input.dataset.formAttribution = "true";
|
|
690
|
+
input.dataset.formAttributionManaged = "true";
|
|
691
|
+
fragment.appendChild(input);
|
|
692
|
+
}
|
|
693
|
+
|
|
694
|
+
if (fragment.hasChildNodes()) {
|
|
695
|
+
form.appendChild(fragment);
|
|
696
|
+
}
|
|
697
|
+
};
|
|
698
|
+
|
|
699
|
+
const injectIntoForms = (data) => {
|
|
700
|
+
const forms = getTargetForms();
|
|
701
|
+
|
|
702
|
+
if (forms.length === 0) {
|
|
703
|
+
log("No forms found on page");
|
|
704
|
+
return;
|
|
705
|
+
}
|
|
706
|
+
|
|
707
|
+
const entries = getAttributionEntries(data);
|
|
708
|
+
|
|
709
|
+
for (const form of forms) {
|
|
710
|
+
syncFormAttributionFields(form, entries);
|
|
711
|
+
|
|
712
|
+
log(
|
|
713
|
+
"Synced attribution fields in form:",
|
|
714
|
+
form.id || form.name || "[unnamed]"
|
|
715
|
+
);
|
|
716
|
+
}
|
|
717
|
+
|
|
718
|
+
log(
|
|
719
|
+
entries.length === 0
|
|
720
|
+
? `Cleared attribution fields in ${forms.length} form(s)`
|
|
721
|
+
: `Injected attribution data into ${forms.length} form(s)`
|
|
722
|
+
);
|
|
723
|
+
};
|
|
724
|
+
|
|
725
|
+
const setupFormObserver = (getData) => {
|
|
726
|
+
const pendingForms = new Set();
|
|
727
|
+
let scheduled = false;
|
|
728
|
+
|
|
729
|
+
const flush = () => {
|
|
730
|
+
scheduled = false;
|
|
731
|
+
if (pendingForms.size === 0) {
|
|
732
|
+
return;
|
|
733
|
+
}
|
|
734
|
+
|
|
735
|
+
const entries = getAttributionEntries(getData());
|
|
736
|
+
for (const form of pendingForms) {
|
|
737
|
+
if (document.contains(form)) {
|
|
738
|
+
syncFormAttributionFields(form, entries);
|
|
739
|
+
}
|
|
740
|
+
}
|
|
741
|
+
pendingForms.clear();
|
|
742
|
+
};
|
|
743
|
+
|
|
744
|
+
const scheduleFlush = () => {
|
|
745
|
+
if (scheduled) {
|
|
746
|
+
return;
|
|
747
|
+
}
|
|
748
|
+
scheduled = true;
|
|
749
|
+
|
|
750
|
+
if (typeof queueMicrotask === "function") {
|
|
751
|
+
queueMicrotask(flush);
|
|
752
|
+
} else {
|
|
753
|
+
Promise.resolve().then(flush);
|
|
754
|
+
}
|
|
755
|
+
};
|
|
756
|
+
|
|
757
|
+
const addFormIfIncluded = (form) => {
|
|
758
|
+
if (shouldIncludeForm(form)) {
|
|
759
|
+
pendingForms.add(form);
|
|
760
|
+
}
|
|
761
|
+
};
|
|
762
|
+
|
|
763
|
+
const collectFormsFromNode = (node) => {
|
|
764
|
+
if (node.tagName === "FORM") {
|
|
765
|
+
addFormIfIncluded(node);
|
|
766
|
+
}
|
|
767
|
+
|
|
768
|
+
if (node.querySelectorAll) {
|
|
769
|
+
const nestedForms = node.querySelectorAll("form");
|
|
770
|
+
for (const form of nestedForms) {
|
|
771
|
+
addFormIfIncluded(form);
|
|
772
|
+
}
|
|
773
|
+
}
|
|
774
|
+
};
|
|
775
|
+
|
|
776
|
+
const processAddedNodes = (addedNodes) => {
|
|
777
|
+
for (const node of addedNodes) {
|
|
778
|
+
if (node.nodeType !== Node.ELEMENT_NODE) {
|
|
779
|
+
continue;
|
|
780
|
+
}
|
|
781
|
+
collectFormsFromNode(node);
|
|
782
|
+
}
|
|
783
|
+
};
|
|
784
|
+
|
|
785
|
+
const handleMutations = (mutations) => {
|
|
786
|
+
for (const mutation of mutations) {
|
|
787
|
+
processAddedNodes(mutation.addedNodes);
|
|
788
|
+
}
|
|
789
|
+
|
|
790
|
+
if (pendingForms.size > 0) {
|
|
791
|
+
scheduleFlush();
|
|
792
|
+
}
|
|
793
|
+
};
|
|
794
|
+
|
|
795
|
+
const observer = new MutationObserver(handleMutations);
|
|
796
|
+
|
|
797
|
+
if (!document.body) {
|
|
798
|
+
log("Form observer could not initialize: document.body not found");
|
|
799
|
+
return observer;
|
|
800
|
+
}
|
|
801
|
+
|
|
802
|
+
observer.observe(document.body, {
|
|
803
|
+
childList: true,
|
|
804
|
+
subtree: true,
|
|
805
|
+
});
|
|
806
|
+
|
|
807
|
+
log("Form observer initialized");
|
|
808
|
+
return observer;
|
|
809
|
+
};
|
|
810
|
+
|
|
811
|
+
const init = async () => {
|
|
812
|
+
log("Initializing with config:", CONFIG);
|
|
813
|
+
|
|
814
|
+
const storage = createStorageAdapter(CONFIG.storage);
|
|
815
|
+
let latestData = null;
|
|
816
|
+
|
|
817
|
+
const existingData = await storage.get(CONFIG.storageKey);
|
|
818
|
+
log("Existing attribution data:", existingData);
|
|
819
|
+
|
|
820
|
+
const currentData = captureAttributionData();
|
|
821
|
+
log("Current attribution data:", currentData);
|
|
822
|
+
|
|
823
|
+
const mergedData = mergeAttributionData(existingData, currentData);
|
|
824
|
+
latestData = mergedData;
|
|
825
|
+
log("Merged attribution data:", mergedData);
|
|
826
|
+
|
|
827
|
+
if (Object.keys(mergedData).length > 0) {
|
|
828
|
+
await storage.set(CONFIG.storageKey, mergedData);
|
|
829
|
+
log("Attribution data saved");
|
|
830
|
+
}
|
|
831
|
+
|
|
832
|
+
injectIntoForms(latestData);
|
|
833
|
+
|
|
834
|
+
setupFormObserver(() => latestData);
|
|
835
|
+
|
|
836
|
+
log("Initialization complete");
|
|
837
|
+
};
|
|
838
|
+
|
|
839
|
+
const run = async () => {
|
|
840
|
+
if (isPrivacySignalEnabled()) {
|
|
841
|
+
log("Tracking disabled due to privacy signal (GPC/DNT)");
|
|
842
|
+
return;
|
|
843
|
+
}
|
|
844
|
+
|
|
845
|
+
if (document.readyState === "loading") {
|
|
846
|
+
document.addEventListener(
|
|
847
|
+
"DOMContentLoaded",
|
|
848
|
+
() => {
|
|
849
|
+
init().catch((e) => log("Initialization error:", e));
|
|
850
|
+
},
|
|
851
|
+
{ once: true }
|
|
852
|
+
);
|
|
853
|
+
} else {
|
|
854
|
+
await init().catch((e) => log("Initialization error:", e));
|
|
855
|
+
}
|
|
856
|
+
};
|
|
857
|
+
|
|
858
|
+
run();
|
|
859
|
+
})();
|
package/package.json
ADDED
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "form-attribution",
|
|
3
|
+
"version": "1.0.0",
|
|
4
|
+
"description": "Automatically capture and persist marketing attribution data in your web forms.",
|
|
5
|
+
"homepage": "https://github.com/flash-brew-digital/form-attribution#readme",
|
|
6
|
+
"sideEffects": false,
|
|
7
|
+
"type": "module",
|
|
8
|
+
"main": "dist/script.js",
|
|
9
|
+
"files": [
|
|
10
|
+
"dist/script.js"
|
|
11
|
+
],
|
|
12
|
+
"repository": {
|
|
13
|
+
"type": "git",
|
|
14
|
+
"url": "git+https://github.com/flash-brew-digital/form-attribution.git"
|
|
15
|
+
},
|
|
16
|
+
"keywords": [
|
|
17
|
+
"forms",
|
|
18
|
+
"lead-generation",
|
|
19
|
+
"attribution",
|
|
20
|
+
"marketing",
|
|
21
|
+
"utm",
|
|
22
|
+
"analytics",
|
|
23
|
+
"crm"
|
|
24
|
+
],
|
|
25
|
+
"author": {
|
|
26
|
+
"name": "Ben Sabic",
|
|
27
|
+
"url": "https://bensabic.ca"
|
|
28
|
+
},
|
|
29
|
+
"license": "Apache-2.0",
|
|
30
|
+
"bugs": {
|
|
31
|
+
"url": "https://github.com/flash-brew-digital/form-attribution/issues"
|
|
32
|
+
},
|
|
33
|
+
"scripts": {
|
|
34
|
+
"release": "npm publish --access public",
|
|
35
|
+
"check": "npx ultracite check",
|
|
36
|
+
"fix": "npx ultracite fix",
|
|
37
|
+
"test": "npx playwright test"
|
|
38
|
+
},
|
|
39
|
+
"devDependencies": {
|
|
40
|
+
"@biomejs/biome": "2.3.10",
|
|
41
|
+
"@playwright/test": "^1.57.0",
|
|
42
|
+
"@types/node": "^25.0.3",
|
|
43
|
+
"ultracite": "6.5.0"
|
|
44
|
+
},
|
|
45
|
+
"packageManager": "pnpm@10.24.0+sha512.01ff8ae71b4419903b65c60fb2dc9d34cf8bb6e06d03bde112ef38f7a34d6904c424ba66bea5cdcf12890230bf39f9580473140ed9c946fef328b6e5238a345a"
|
|
46
|
+
}
|