Skip to content

Commit 709ed40

Browse files
Track element's data attributes if present
1 parent b1d6f3d commit 709ed40

2 files changed

Lines changed: 28 additions & 2 deletions

File tree

index.html

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -27,5 +27,6 @@
2727
</div>
2828
</div>
2929
<a href="/" id="link5" data-ahoy-skip="true"><span>Link 5</span></a>
30+
<a href="/" id="link6" data-foo="bar"><span>Link 6</span></a>
3031
</body>
3132
</html>

src/index.js

Lines changed: 27 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -267,21 +267,46 @@ function presence(str) {
267267
function cleanObject(obj) {
268268
for (const key in obj) {
269269
if (Object.prototype.hasOwnProperty.call(obj, key)) {
270-
if (obj[key] === null) {
270+
const value = obj[key];
271+
272+
if (value === null || isLiteralObject(value) && isEmpty(value)) {
271273
delete obj[key];
272274
}
273275
}
274276
}
275277
return obj;
276278
}
277279

280+
function isLiteralObject(obj) {
281+
return (!!obj) && (obj.constructor === Object);
282+
}
283+
284+
function getDatasetInKebabCase(element) {
285+
const datasetInKebabCase = {};
286+
287+
for (const attrName in element.attributes) {
288+
if (Object.prototype.hasOwnProperty.call(element.attributes, attrName)) {
289+
const attr = element.attributes[attrName];
290+
291+
if (attr.name.startsWith('data-')) {
292+
const keyWithoutDataPrefix = attr.name.replace('data-', '');
293+
294+
datasetInKebabCase[keyWithoutDataPrefix] = attr.value;
295+
}
296+
}
297+
}
298+
299+
return datasetInKebabCase;
300+
}
301+
278302
function eventProperties() {
279303
return cleanObject({
280304
tag: this.tagName.toLowerCase(),
281305
id: presence(this.id),
282306
"class": presence(this.className),
283307
page: page(),
284-
section: getClosest(this, "data-section")
308+
section: getClosest(this, "data-section"),
309+
data: getDatasetInKebabCase(this)
285310
});
286311
}
287312

0 commit comments

Comments
 (0)