Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detect working CustomEvent constructor

Tags:

javascript

I want to test whether the CustomEvent constructor is supported.

var ev;

if (/* CustomEvent constructor supported? */) {
    ev = new CustomEvent('splat');
} else {
    ev = document.createEvent('Event');
    ev.initEvent('splat');
}

this.dispatchEvent(ev);

I don't have any machines running IE nearby to test it. Does it throw an error so I can use try/catch, or do I need to do something else? What about older non-IE browsers?

like image 714
Dagg Nabbit Avatar asked Jan 06 '14 18:01

Dagg Nabbit


2 Answers

The following should work, even on IE6, i've tested it on an old XP machine with IE6.

if (typeof CustomEvent === 'function') {
    ev = new CustomEvent('splat');
}
like image 118
Jelle Kralt Avatar answered Nov 03 '22 05:11

Jelle Kralt


Yeah, try/catch should work, ie8 will throw:

TypeError: 'CustomEvent' is undefined

Whereas ie11 will throw:

Object doesn't support this action

Other older browsers will either have not implemented it at all, or not as a constructor, so should result in similar errors

so you could do something like:

var isSupported = (function() { 
  try {
    new CustomEvent('test');
    return true;
  } catch (e) {
    return false;
  }
})();
like image 20
j_ernst Avatar answered Nov 03 '22 05:11

j_ernst