Check if optional chaining is supported
Asked Answered
I

3

6

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 ?

Iterative answered 20/2, 2021 at 7:2 Comment(0)
R
7

This works:

const isOptionalChainingSupported = () => {
  try {
    eval('const foo = {}; foo?.bar');
  } catch {
    return false;
  }

  return true;
}
Renvoi answered 11/11, 2021 at 22:42 Comment(1)
This should be } catch (e) { as the whole function will error out on internet exploder without it.Endometrium
I
0

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
  }
}
Iterative answered 20/2, 2021 at 7:2 Comment(7)
You can drop the if statement. The condition always evaluates to true.Floppy
To be more precise: It would always fall in the catch if it throws, rather than always evaluates to true. Removed the condition :)Iterative
I've tried this approach, but it didn't work. It throws an Uncaught SyntaxError when there's no support, which doesn't work with try/catch. Is there something else I must do to make it work?Spin
@LincolnAlves I had the same problem. My open source contributor solved it by putting the detection algorithm in a file that's dynamically loaded. Look here: github.com/stephanrauh/ngx-extended-pdf-viewer/blob/main/… and github.com/stephanrauh/ngx-extended-pdf-viewer/blob/….Floppy
Hey @StephanRauh ! Actually I'm the one who mad that contribution hahah! I was still searching for the best approach when I asked here!Spin
Oops - I knew your name sounds familiar :)Floppy
This results in a syntax error when optional chaining is not supportedAllophane
O
0

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)

Octangle answered 29/9 at 19:25 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.