Skip to content

Commit b43ade7

Browse files
authored
Merge pull request #12 from contexD/ie11-json-parse-bug
IE11 json parse bug
2 parents 6927b7d + 983ebb9 commit b43ade7

2 files changed

Lines changed: 32 additions & 3 deletions

File tree

src/abode.ts

Lines changed: 13 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -80,10 +80,20 @@ export const getElementProps = (el: Element | HTMLScriptElement): Props => {
8080
attribute.name.startsWith('data-prop-')
8181
);
8282
rawProps.forEach(prop => {
83-
try {
84-
props[getCleanPropName(prop.name)] = JSON.parse(prop.value);
85-
} catch (e) {
83+
if (/^0+\d+$/.test(prop.value)) {
84+
/*
85+
ie11 bug fix;
86+
in ie11 JSON.parse will parse a string with leading zeros followed
87+
by digits, e.g. '00012' will become 12, whereas in other browsers
88+
an exception will be thrown by JSON.parse
89+
*/
8690
props[getCleanPropName(prop.name)] = prop.value;
91+
} else {
92+
try {
93+
props[getCleanPropName(prop.name)] = JSON.parse(prop.value);
94+
} catch (e) {
95+
props[getCleanPropName(prop.name)] = prop.value;
96+
}
8797
}
8898
});
8999
}

test/abode.test.tsx

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -66,6 +66,7 @@ describe('helper functions', () => {
6666
abodeElement.setAttribute('data-prop-number-prop', '12345');
6767
abodeElement.setAttribute('data-prop-null-prop', 'null');
6868
abodeElement.setAttribute('data-prop-true-prop', 'true');
69+
abodeElement.setAttribute('data-prop-leading-zeros', '0012');
6970
abodeElement.setAttribute('data-prop-empty-prop', '');
7071
abodeElement.setAttribute(
7172
'data-prop-json-prop',
@@ -79,6 +80,7 @@ describe('helper functions', () => {
7980
numberProp: 12345,
8081
nullProp: null,
8182
trueProp: true,
83+
leadingZeros: '0012',
8284
emptyProp: '',
8385
jsonProp: { id: 12345, product: 'keyboard', variant: { color: 'blue' } },
8486
});
@@ -94,6 +96,23 @@ describe('helper functions', () => {
9496
);
9597
});
9698

99+
it('getElementProps does not parse strings with leading zeros followed by other digits', () => {
100+
const strWithLeadingZeros = fc
101+
.tuple(fc.integer(1, 10), fc.integer())
102+
.map(t => {
103+
const [numberOfZeros, integer] = t;
104+
return '0'.repeat(numberOfZeros) + integer.toString();
105+
});
106+
fc.assert(
107+
fc.property(strWithLeadingZeros, data => {
108+
const abodeElement = document.createElement('div');
109+
abodeElement.setAttribute('data-prop-test-prop', data);
110+
const props = getElementProps(abodeElement);
111+
expect(props.testProp).toEqual(data);
112+
})
113+
);
114+
});
115+
97116
it('setAttributes', () => {
98117
const abodeElement = document.createElement('div');
99118

0 commit comments

Comments
 (0)