Feature detection in the browser with capital leaders (illegal identifiers)

I can paste in some %raw js, but curious if there’s a way to do this without resorting to that:

type audioContext

let createAudioContext: unit => option<audioContext> = () => {
  let audioContext = %raw(`typeof AudioContext !== "undefined" ? AudioContext : 
  typeof webkitAudioContext !== "undefined" ? webkitAudioContext :
  typeof mozAudioContext !== "undefined" ? mozAudioContext : null`)

  let instance = %raw(`function (AudioContext) { return !!AudioContext ? new AudioContext() : null}`)(
    audioContext,
  )

  instance
}

I need to use new to instantiate the class, but I don’t know the exact name ahead of time, and I can’t rely on any of them being there (assuming e.g. SSR).

You mean like this? Bind to Global JS Values | ReScript Language Manual

Something like this?

type audioContext

@new external createAudioContext: unit => audioContext = "AudioContext"

let createAudioContext: unit => option<audioContext> = () => {
  switch %external(\"AudioContext") {
  | Some(_) => createAudioContext()->Some
  | None => None
  }
}
2 Likes

Yes, exactly that - I suppose I could make another createWebkitAudioContext and an additional switch %external... for that.

Makes sense, thank you!