Skip to content

Commit 5a33bbd

Browse files
committed
feat: update attibutes using keyObperators on storage change or event updateAttributes
1 parent 7f6777f commit 5a33bbd

File tree

1 file changed

+39
-11
lines changed

1 file changed

+39
-11
lines changed

src/getAttribute.js

+39-11
Original file line numberDiff line numberDiff line change
@@ -1,23 +1,51 @@
11
// Store a reference to the original getAttribute function
22
const originalGetAttribute = Element.prototype.getAttribute;
3+
const attributes = new Map()
4+
5+
window.addEventListener('storage', updateAttributes);
6+
window.addEventListener('updateAttributes', function (e) {
7+
updateAttributes(e.detail);
8+
});
9+
10+
function updateAttributes(e) {
11+
const keys = ['organization_id', 'user_id', 'clientId', 'session_id'];
12+
if (keys.includes(e.key)) {
13+
let attr = attributes.get(e.key) || []
14+
for (let attribute of attr) {
15+
attribute.element.setAttribute(attribute.name, e.newValue)
16+
}
17+
}
18+
}
319

420
// Override the getAttribute function
521
Element.prototype.getAttribute = function (name) {
622
let value = originalGetAttribute.call(this, name);
723

8-
if (value === '$organization_id')
9-
value = localStorage.getItem('organization_id')
10-
else if (value === '$user_id')
11-
value = localStorage.getItem('user_id')
12-
else if (value === '$clientId')
13-
value = localStorage.getItem('clientId')
14-
else if (value === '$session_id')
15-
value = localStorage.getItem('session_id')
16-
else if (value === '$innerWidth')
24+
const localKeys = {
25+
'$organization_id': 'organization_id',
26+
'$user_id': 'user_id',
27+
'$clientId': 'clientId',
28+
'$session_id': 'session_id'
29+
};
30+
31+
if (localKeys[value]) {
32+
let newValue = localStorage.getItem(localKeys[value]);
33+
34+
if (!attributes.has(localKeys[value])) {
35+
attributes.set(localKeys[value], []);
36+
}
37+
38+
attributes.get(localKeys[value]).push({
39+
element: this,
40+
name,
41+
value: newValue
42+
});
43+
value = newValue
44+
} else if (value === '$innerWidth') {
1745
value = window.innerWidth
18-
else if (value === '$innerHeight')
46+
} else if (value === '$innerHeight') {
1947
value = window.innerHeight
20-
else if (typeof value === 'string') {
48+
} else if (typeof value === 'string') {
2149
if (value.startsWith('$search')) {
2250
const searchParams = new URLSearchParams(window.location.search);
2351
if (value.includes('.')) {

0 commit comments

Comments
 (0)