1

Normally if you want to check if a feature is supported in a browser, you'd do a simple if statement like this:

if (SomeFooFeature) { ... }

So in my application, I check for the AudioContext object, to avoid errors when trying to use it if it is not supported:

if (AudioContext) {
    context = new AudioContext()
}

But when I do that, IE complains that "AudioContext" is undefined. Uhm, what? Didn't I just check for that?

Infact, just doing if (Foo) { ... } gives the same error.

Why? How can something this trivial not work in Internet Explorer?

Sebastian Olsen
  • 10,318
  • 9
  • 46
  • 91

1 Answers1

4

Try doing this

if (typeof AudioContext != "undefined") {
    context = new AudioContext()
}
Sebastian Olsen
  • 10,318
  • 9
  • 46
  • 91
Santiago Bendavid
  • 961
  • 1
  • 9
  • 16
  • That worked. Is it just me who thinks it's plain idiotic that this does not work in IE? – Sebastian Olsen May 10 '16 at 16:03
  • It works nowhere else either. It's standard behavior that you have to have a variable declared somewhere (either from your environment, from a `var` statement or from a function argument) before referencing it. – CherryDT May 10 '16 at 16:03
  • @CherryDT But why does if (window.AudioContext) work then? – Sebastian Olsen May 10 '16 at 16:04
  • 3
    Because the `window` variable is defined. You are checking for a property of the `window` object, which is fine. Try `console.log(abc);`(reference error) and `var x = {}; console.log(x.abc);` (no error, undefined) to see what I mean. It's just a "coincidence" (defined by the browser) that `window` is also the global object here, it's not a feature of the language itself. – CherryDT May 10 '16 at 16:05
  • @CherryDT Oh, man I feel stupid. That does make a lot more sense. Is it okay to just check for window.AudioContext in the if statement, then? – Sebastian Olsen May 10 '16 at 16:06
  • @SebastianOlsen I would strongly recommend to always use typeof instead. It's kind of standard in JavaScript to do that validation. – Santiago Bendavid May 10 '16 at 16:08
  • 1
    Personally I find `if(window.AudioContext)` nicer to read because no string is involved, but I guess it's a matter of taste because it makes no real difference except for the fact that if `AudioContext` is not an object but the number zero (or false or null, ...) the `typeof` will yield true but the other method will yield false. But in this case you are screwed anyway because to prevent things called `AudioContext` which are no real `AudioContext` from sneaking in, you would need to do all kinds of other checks ^^ – CherryDT May 10 '16 at 16:10
  • @CherryDT In that case, using window.AudioContext works perfectly in my situation. – Sebastian Olsen May 10 '16 at 16:11