I want to use a polyfill for optional chaining but I do not want to provide a polyfill for browsers which already support this feature.
Is there a way to determine whether a browser supports optional chaining ?
I want to use a polyfill for optional chaining but I do not want to provide a polyfill for browsers which already support this feature.
Is there a way to determine whether a browser supports optional chaining ?
This works:
const isOptionalChainingSupported = () => {
try {
eval('const foo = {}; foo?.bar');
} catch {
return false;
}
return true;
}
I couldn't find any solutions online. I managed to come up with this:
const getIsOptionalChainingSupported = () => {
try {
const test = {};
const isUndefined = test?.foo?.bar
if (isUndefined === undefined) {
return true
}
} catch {
return false
}
}
if
statement. The condition always evaluates to true
. –
Floppy true
. Removed the condition :) –
Iterative The only solution that works for me is by adding a script tag in header, then defend a global var
<script>
let a = {};
a?.a?.a;
var supportsOpChaining = true;
</script>
then
if (typeof supportsOpChaining !== "undefined"){
// The code that uses optional chaining
}
else {
// The code that not using optional chaining
}
(I'm adding 'unsafe-eval' to my site header, so i can't use eval)
© 2022 - 2024 — McMap. All rights reserved.
} catch (e) {
as the whole function will error out on internet exploder without it. – Endometrium